I need a way in a C preprocessor #if to test if a value will create a 0-size array

58

I have a structure that must pad out to 64K to fit perfectly in an embedded project, so that it fills out a flash block. So there is a #define that adds up the elements in the structure using sizeof() and determines how big the pad[] at the end needs to be to cause the total size to be 64K.

For example,

#define SIZE_OF_MY_PAD (0x10000 - (sizeof(uint16_t) + sizeof(uint8_t)*32 + ... ))

typedef struct {
  uint16_t firstElement;
  uint8_t  secondElementArray[32];
  ...
  uint8_t pad[SIZE_OF_MY_PAD];
};

This has worked great for a long time until suddenly we don't need the pad at all in certain build configurations because it is already exactly 64k. This causes the code to fail because our compiler (not GCC) does not allow pad[0].

I have tried various ways to create a preprocessor value that I can use in an #if statement when this is detected, but it always fails because although sizeof() is legal in #define, it is not legal in #if.

Share
Improve this question
5
  • 6
    Add a static assert on the sizeof of the struct. You can't adjust the size of the padding in compile time, but you can make it to fail the compilation in case it is not correct. – Eugene Sh. Apr 7 at 19:05
  • 8
    While a good question, this is something probably better solved in the linker, not the compiler. – pipe Apr 8 at 8:37
  • @rd-florida Can you identify what compiler you use? Is it C11 compatible? – Ross Presser Apr 8 at 13:11
  • 9
    @pipe: I disagree. Keep the linker out of this. You sanity will thank you. – Joshua Apr 8 at 21:14
  • 3
    I would recommend to place this code in a dedicated section (#pragma section) and then place the section where you want in the linker script. – prapin Apr 9 at 19:49

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue