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?
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[] = { ...};
It issues the warning because the array is not referenced in the code. Comment the array out and the warning will go away.
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.
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).
精彩评论