Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 500
bodacydo Avatar asked Aug 06 '10 06:08

bodacydo


People also ask

Can we use extern in header file?

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.

What is header file array in C?

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.

Can I define an array in a header file?

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.

What is extern in C code?

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.


2 Answers

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
like image 155
Praveen S Avatar answered Sep 28 '22 00:09

Praveen S


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 */
like image 24
schot Avatar answered Sep 28 '22 02:09

schot