So I want to have a definition of the size of an array within a struct known at compile time. I would also like that number available as a variable for ease of use later. What I have is the following:
const int BANANA_ARRAY_SIZE = 10;
typedef struct
{
char bananas[BANANA_ARRAY_SIZE];
int some_other_stuff;
} banana_struct;
This functions fine. However, if I have it in a .h file that gets included in multiple places, the compiler complains about redefinition of BANANA_ARRAY_SIZE (which makes sense). So I need to declare it as an extern so multiple compilation units can know about it.
So, I now have
extern const int BANANA_ARRAY_SIZE;
typedef struct
{
//.. same as before
} banana_struct;
and in an implementation file I have
const int BANANA_ARRAY_SIZE = 10;
But now the compiler won't let me define the struct anymore with complaints of
fields must have a constant size: variable length array in structure
Is there any way I can achieve what I want (have length of array stored in variable and used to define struct)?
Edit:
In response to the suggestions to instead use #define
s, I'd rather not.
My question is about how to have this constant value stored in a variable and also used to set the length of an array in a struct. If you need further justification, assume I need a function that takes a pointer to an int. Can't take a reference of a #define.