tags:

views:

86

answers:

4

I have the following static array in header file:

static MyStruct_t MyStructArray[] = {
    ......
    ......
    ......     
}

But gcc issues a warning:

warning: `MyStructArray' defined but not used

What is the correct way to handle the situation?

UPD:

Defining the array as const:

const MyStruct_t MyStructArray[] = {
    ......

fixes thwe situation. So what is the preferred way extern or const in header?

+1  A: 

It issues the warning because the array is not referenced in the code. Comment the array out and the warning will go away.

RA
It's not reference in "all" cpp files, but in some cpp files it's used.
dimba
@idimba Yes and by using the static keyword you get a distinct array in each cpp file. So some of these arrays are really not referenced.
Alexandre Jasmin
+4  A: 

Because you've declared the array static in a header file, each compilation unit (i.e. preprocessed .cpp file) gets its own copy of the array--almost certainly not what you intended, and the sure reason that you get the "defined but not used" error.

Instead, you probably want this in your header file:

extern MyStruct_t *MyStructArray;

...and then in exactly 1 .cpp file:

MyStruct_t MyStructArray[] = { ...};
Drew Hall
I was thinking of extern, but thought that the array must be defined as "extern MyStruct_t MyStructArray[];". Does it matters at all in this context?
dimba
@idimba: That would work, too. In fact, it's probably more correct than what I said.
Drew Hall
+1  A: 

As the error message says, the array is defined, but not used. If you don't want to use it, well ... don't define it!

Also, it looks strange that you want it static and you define it in a header file. These are opposite things.

The correct way to handle this, is to declare the array in the header file:

MyStruct_t MyStructArray[];

And to define it in one C file (one compilation unit).

MyStruct_t MyStructArray[] = {
    ......
    ......
    ......     
}

But note that you cannot have it static this way.

Didier Trosset
+1  A: 

If this array is intended to be public then you most likely want to make it extern as opposed to static (which is what causes the warning).

Ciarán Walsh