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.
Maybe something like this is what you want:
... some declaration of my_array ... #define MAX_SIZE 5000 /* bytes, for example */ typedef int dummy[sizeof(my_array) <= MAX_SIZE ? 1 : -1];
If the size of the array is small enough this will create a legal typedef named dummy that we don't actually use.
If the size is too big then the typedef is illegal an the compiler should give an error.
Some compilers/mode allow zero length arrays, but I haven't met one that allows -1 length arrays.
What he means is that he wants to constrain the size (number of elements) of the array by specifically limiting the amount of RAM that it is allowed to occupy.
Yes, I know that is what the OP means, what I was trying to establish is what the curious jumble of words posted by you know who was all about?
how do you have an array that is larger (the number of elements) than "the amount of RAM the array consumes"
That's an interesting combination of words you've posted there. Is it some sort of answer to the OP's question?
I don't want to limit the number of elements but the amount of RAM the array consumes
Erik
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 - 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)];
"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?
Tamir/Blip (OATS)
You can see an interesting article on assert_static here
www.drdobbs.com/184401873
For things like this I normally use the assert_static() macro. Look it up in google.
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.
But, surely, there is a direct, 1:1 relationship between the two?!
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.
I don't want to limit the number of elements but the amount of RAM the array consumes - and to enforce that during compilation.
Why?
Can't you just do:
#define ARRAY_SIZE my_type my_array[ARRAY_SIZE];
View all questions in Keil forum