#define issues

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

#define issues

2,199 Views
bob_s
Contributor III
I've run into the following problem with using calculated defines with the compiler.

These three defined in a bean:
//#define DATA_FLASH_SECTOR_SIZE 256u  
//#define DATA_FLASH_END   8191                  
//#define DATA_FLASH_START 4096

These were my defines:
#define NVRAM_SECTORS_RESERVE    4
#define MAX_SECTORS    ((DATA_FLASH_END +1 - DATA_FLASH_START)/DATA_FLASH_SECTOR_SIZE) - NVRAM_SECTORS_RESERVE
#define BLK_SIZE 16
#define MAX_BLKS  (MAX_SECTORS * (DATA_FLASH_SECTOR_SIZE / BLK_SIZE))

MAX_SECTORS calculated correctly to 12 but MAX_BLKS calculated to some number about 65k when it should be 192.  I've had to enter it's value literally to make it work.

Is there a mistake here or is the compiler not able to handle the sequential number of calculations required to get to the value requested? 

I'm concerned if there is some limitation I need to know about.

Thanks.  Bob
Labels (1)
0 Kudos
3 Replies

413 Views
CompilerGuru
NXP Employee
NXP Employee
There is a pair of parentheses missing in the MAX_SECTORS macro.
As it is, the
Code:
#define MAX_BLKS  (MAX_SECTORS * (DATA_FLASH_SECTOR_SIZE / BLK_SIZE))

 
macro expands to
Code:
#define MAX_BLKS  (((DATA_FLASH_END +1 - DATA_FLASH_START)/DATA_FLASH_SECTOR_SIZE) - NVRAM_SECTORS_RESERVE * (DATA_FLASH_SECTOR_SIZE / BLK_SIZE))

 
so only NVRAM_SECTORS_RESERVE gets multiplied and not the value of NVRAM_SECTORS_RESERVE.

In general in C all but the most simple macros should start with a opening paranthesis and close with a closing one. In addition for macros with arguments, the argument should be enclosed in parentheses too.

So MAX_SECTORS should be defined as:
Code:
#define MAX_SECTORS (((DATA_FLASH_END +1 - DATA_FLASH_START)/DATA_FLASH_SECTOR_SIZE) - NVRAM_SECTORS_RESERVE)

As additional tip, if anything looks wrong with macros, always check the preprocessor output.

Daniel
 

0 Kudos

413 Views
bob_s
Contributor III
Thanks Daniel for your response.

I see why the additional parenthesis needed to be added to 'MAX_SECTORS'.

I looked through the preprocessor file for the 'MAX_BLKS' value, but I did not see it.

Bob

0 Kudos

413 Views
bob_s
Contributor III
I found that the preprocessor sends a formula rather than the result which I found in the preprocess of the code rather than the header file.  That helps.  Thanks Daniel.  Bob
0 Kudos