C ++ static array declared in h file gives a warning “defined but not used”

I am interested in the following. I have a simple C array declared in the header file as follows:

static int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17}; 

he gives me a bunch of warnings:

 : 'userCardsIndexes' defined but not used 

even though I include this file in my cpp files and use this variable. Secondly, I do not understand this when I add the const specifier as follows:

 static const int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17}; 

warnings disappear! Can someone give me an explanation why I get these warnings and why const removes them?

+7
source share
2 answers

Short answer: you define an array in the header, not just declare it. This is not good. If you need an array that is available whenever you include a header, there should be a declaration in the header:

 extern int userCardsIndexes[INITIAL_CARDS_NUMBER]; 

And then, in only one source file, define the array as such:

 int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17}; 

As for the long answer: there is nothing "magic" in the header file; the #include directive simply copies the entire contents of the header file to the source file. Essentially, what you get is the new static array userCardsIndexes defined in each source file; if this array is not used, you get a warning "unused variable". The const conversion probably suppresses the warning only because the compiler is not configured to warn about const unused variables. For example: using GCC, see the documentation for "-Wunused-variable":

http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

+15
source

Static variables are local to the translation unit in which they are defined. When you do this in the header, you get a separate copy in each cpp file in which you include it. This is probably not what you wanted. The compiler obviously notices that some of these copies are not used at all.

When you add const , you have a different situation. In C ++, a const object in a file area is also static by default. So, const and static const mean the same thing.

The constant array will also have a copy in each cpp file, but that doesn't matter much, because in any case it will always have the same value.

+5
source

All Articles