LOSwy LOSwy - 3 years ago 154
C Question

Defining value according a specific value at memory location

I have an issue with defining value according a specific value at memory location.

Basically I want to read a value at specific memory location and create a define from this value. And then use this same define to define again a new value according the first define value when compiling the code.

Here is my example:

#define MY_DEFINE_VALUE (*(uint32_t *)0x0800C200)

// 8 kBytes of EEPROM
// First section base address is 0x08080000
// Second section base address is 0x08081000
#if ( MY_DEFINE_VALUE < 0x0200 )
#define EEPROM_BASE ((uint32_t)0x08080000)
#define EEPROM_BASE ((uint32_t)0x08081000)

Thanks for your help.

Answer Source

You can't solve this in that way, C doesn't work like that. In fact it makes no sense, since you're expecting there two be two different pieces of code in the same place (one that uses 0x08080000 and one that uses 0x08081000).

You're going to have to:

  1. Build two different binaries, and program the board accordingly. This pushes the responsibility for knowing which board needs which binary to outside the software
  2. Check at run-time, and either pick between hardcoded alternatives of the code, or simply do make the access dynamic.

My preference would be dynamic run-time access, which should be fine unless this is in the most performance-critical part of your code.

So, you'd make a variable:

volatile uint32_t *eeprom_base;

and then just add code to set it at run-time:

if (*(uint32_t *) 0x800c200 < 0x200)
  eeprom_base = (uint32_t *) 0x8080000;
  eeprom_base = (uint32_t *) 0x8081000;

then make the accesses through the variable instead of the preprocessor symbol, or change the latter to:

#define EEPROM_BASE    eeprom_base

Of course you're going to have to make sure the variable has a visible declaration in all places where it's being used, too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download