Q: I have an extern array which is defined in one file, and used in another:
file1.c: file2.c: int array[] = {1, 2, 3}; extern int array[];Why doesn't sizeof work on array in file2.c?
A: An extern array of unspecified size is an incomplete type; you cannot apply sizeof to it. sizeof operates at compile time, and there is no way for it to learn the size of an array which is defined in another file.
You have three options:
file1.c: file2.c: int array[] = {1, 2, 3}; extern int array[]; int arraysz = sizeof(array); extern int arraysz;(See also question 6.23.)
file1.h: #define ARRAYSZ 3 extern int array[ARRAYSZ]; file1.c: file2.c: #include "file1.h" #include "file1.h" int array[ARRAYSZ];
file1.c: file2.c: int array[] = {1, 2, 3, -1}; extern int array[];
See also question 6.21.
References:
H&S Sec. 7.5.2 p. 195