0

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?

4 Answers 4

5

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[] = { ...};
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@idimba: That would work, too. In fact, it's probably more correct than what I said.
1

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

2 Comments

It's not reference in "all" cpp files, but in some cpp files it's used.
@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.
1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.