Reputation: 326
Consider the following common array definition, note that the array itself has to includes total size:
#define BUFSZ 3
uint8_t buffer[BUFSZ] = {
BUFSZ, 0xFF, 0x00
}
This is not very handy when you change the buffer alot and it gets large enough that keeping track of every change is easier than counting from scratch each time. Of course, something like this is possible:
#define BUFSZ 3
uint8_t buffer[BUFSZ] = {
sizeof(buffer), 0xFF, 0x00
}
or conversely
#define BUFSZ 3
uint8_t buffer[] = {
BUFSZ, 0xFF, 0x00
}
But a combination of the two rquiring no counting at all is not possible:
uint8_t buffer[] = {
sizeof(buffer), 0xFF, 0x00
}
which results in
invalid application of 'sizeof' to incomplete type 'uint8_t[]' {aka 'unsigned char[]'}
Note I am using the arm-none-eabi-gcc compiler, but this also applies to gcc.
What is the best practice for a situation where you need to define a array at compile time which needs to store its size?
I guess an option could be to reserve that spot and set it at runtime, which in my case could work, but could also prevent it to be saved in read only memory.
Upvotes: 1
Views: 229
Reputation: 68059
#define INIT 0xFF, 0x00
#define SOF(x) (sizeof((char []){x})+1)
char buffer[] =
{
SOF(INIT) , INIT
};
or
#define SOF(name, ...) char name[] = {(sizeof((char []){__VA_ARGS__})+1), __VA_ARGS__}
SOF(buffer,255,0);
Upvotes: 1