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.
ANSWER. Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
The header file -- the whole thing: array.hh file are similar (except a different identifier, ARRAY_H, to match the filename is used): #ifndef ARRAY_H #define ARRAY_H #include < iostream > using namespace std; Consider the class definition.
A global array does not have to be declared in a header file. However, doing so allows the array to be used, without having to copy/paste the declaration to everywhere it is needed.
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
This link discusses the problems with arrays and sizes used as extern and how to manage them.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With