How to declare a global size array defined in another file in C99?

Considering the VLA (variable length array), I would like to ask your opinion on the following problem: If the array is defined in the global scope in one file:

int arr[] = {1, 2, 3};

// in the same file it is no problem to obtain the number of elements in arr by
#define arr_num sizeof(arr)/sizeof(arr[0])
// or
enum {arr_num = sizeof(arr)/sizeof(arr[0])};

The problem is that in other files in the same project, I would like to again create other arrays in the global area with the same number of elements as in the arr. But how can this be achieved in C99 if there is no way to "extern" enum or #define. Of course, you can # determine the number of arr elements manually in the header file, and then use it in other files, but this is very inconvenient, since changing the number of elements in the arr array, you also need to manually change the value of this #define (this is even more inconvenient when arr is an array of structures).

Thanks so much for any help.

+5
source share
2 answers

VLAs do not help with this: they must be automatic variables, and therefore you cannot make a global VLA variable. I agree with valdo that a global variable containing the size of the array (or, alternatively, a function returning it) is the right approach.

+2
source

AFAIK you cannot do this according to C99. Since all translation modules are compiled independently, then you sizeofshould know at compile time.

You can do something like this:

int arr[] = {1, 2, 3};
const int g_arrCount = sizeof(arr)/sizeof(arr[0]);

// other translation unit
extern const int g_arrCount;

- , g_arrCount , .

0

All Articles