dimba
dimba

Reputation: 27581

Defining global array

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?

Upvotes: 0

Views: 1397

Answers (4)

Ciarán Walsh
Ciarán Walsh

Reputation: 1866

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).

Upvotes: 1

Didier Trosset
Didier Trosset

Reputation: 37437

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.

Upvotes: 1

Drew Hall
Drew Hall

Reputation: 29055

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[] = { ...};

Upvotes: 5

ROAR
ROAR

Reputation: 1324

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

Upvotes: 1

Related Questions