Hello,
I want to use the #error directive to limit the size of a statically allocated array during compilation (it must not exceed a certain limit, and I want to fail compilation, not startup, if it is too large), but I can only work with constant expressions, of course. Is there a way to do this...?
Thanks.
I forgot to mention that the array can contain various types and I don't know in advance how many elements are in it.
OK, I can add marker at the beginning and end of the array. Something else...?
Maybe Tamir knows the answer ;)
I have nothing to add at this time. Thanks for inviting me to speak (???).
Why?
Can't you just do:
#define ARRAY_SIZE my_type my_array[ARRAY_SIZE];
I don't want to limit the number of elements but the amount of RAM the array consumes - and to enforce that during compilation.
sizeof would need to be used on structures but that is not available to the pre-processor.
I've done it before with a custom written, post link executable/map verifier.
But, surely, there is a direct, 1:1 relationship between the two?!
I guess it is also possible to generate a linker error by mapping the array to a region that is limited in size in RAM.
For things like this I normally use the assert_static() macro. Look it up in google.
Tamir/Blip (OATS)
You can see an interesting article on assert_static here
www.drdobbs.com/184401873
"I forgot to mention that the array can contain various types and I don't know in advance how many elements are in it."
Arrays hold elements of a single type. What do you mean by "the array can contain various types"? How are you implementing an array containing various types?
"I don't want to limit the number of elements but the amount of RAM the array consumes - and to enforce that during compilation."
Then ignoring your "various types" requirement, Andy's example becomes:
#define MY_ARRAY_SIZE_MAX 4096 /* Limit array to 4K total */ my_type my_array[MY_ARRAY_SIZE_MAX / sizeof(my_type)];
As I recall:
my_type my_array[MY_ARRAY_SIZE_MAX / sizeof(my_type my_array[0])];
takes care of the type size.
I don't want to limit the number of elements but the amount of RAM the array consumes
how do you have an array that is larger (the number of elements) than "the amount of RAM the array consumes"
Erik