views:

111

answers:

2

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];

But this results in compiler errors:

water.h:5: error: array type has incomplete element type

I can't figure it out.

Thanks, Boda Cydo.

+2  A: 

This link discusses the problems with arrays and sizes used as extern and how to manage them.

  1. 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
  2. #define a manifest constant for the size so that it can be used consistently in the definition and the extern declaration
  3. 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
Praveen S
+1 for mentioning array size. The compiler simply has no information about the size of the array if it isn't explicitly declared in the header file
chrmue
I don't believe this is the OP's problem or question: He doesn't want to know the size of his arrays, he just wants to properly declare them. Links the the C-FAQ are always good of course.
schot
+1  A: 

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 */
schot
Thanks, Let me verify.
bodacydo