How to correctly write declarations of extern arrays (and double arrays) in C's header files?
Suppose I want to share a global array of data across my program, for example:
int lookup_indexes[] = { -1, 1, 1, -1, 2, 1, 1, -2, 2, 2, -1, 1, 1, 2 };
What is the correct extern
declaration for this array in the C header file?
Also what about an array like this:
int double_indexes[][5] = { { -1, 1, 1, -1, 1 }, { 2, -2, 2, 1, -1 } };
In my header file I tried this:
extern int lookup_indexes[];
extern int double_indexes[][5];
Bu开发者_运维百科t this results in compiler errors:
water.h:5: error: array type has incomplete element type
I can't figure it out.
Thanks, Boda Cydo.
This link discusses the problems with arrays and sizes used as extern and how to manage them.
- Declare a companion variable, containing the size of the array, defined and initialized (with sizeof) in the same source file where the array is defined
define a manifest constant for the size so that it can be used consistently in the definition and the extern declaration
- Use some sentinel value (typically 0, -1, or NULL) in the array's last element, so that code can determine the end without an explicit size indication
The code you posted looks fine to me and compiles (gcc -std=c99 -pedantic
and gcc -std=c90 -pedantic
) on my machine. Have you copy-pasted these lines or could you have made a typo in your real header?
Example typos that could cause your error (pure guesswork):
extern int double_indexes[][]; /* forgot the 5 */
extern int double_indexes[5][]; /* [] and [5] swapped */
精彩评论