Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ static array declared in h file gives warning 'defined but not used'

I'm curious about the following. I have a simple C array declared in a header file like this:

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

it gives me a bunch of the warnings:

: 'userCardsIndexes' defined but not used

despite i include this file into my cpp files and use this variable. The second thing that i don't understand about it is when i add const specifier like this:

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

the warnings disappear! Can anyone give me an explanation why i get these warnings and why const removes them?

like image 798
Andrey Chernukha Avatar asked Jan 27 '13 09:01

Andrey Chernukha


2 Answers

The short answer is: you're defining an array in a header, not just declaring it. This is not good. If you need the array accessible whenever you include the header, there should be a declaration in the header as such:

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 to the long answer: there's nothing "magical" about a header file; the #include directive just basically copies the entire contents of the header file into your source file. So essentially, what you're getting is a new static array userCardsIndexes defined in every source file; if this array isn't used, you get the "unused variable" warning. Prepending the const is likely suppressing the warning just because the compiler isn't configured to warn on const unused variables. For example: using GCC, look at the documentation for "-Wunused-variable":

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

like image 157
sheu Avatar answered Sep 19 '22 15:09

sheu


Static variables are local to the translation unit they are defined in. When you do that in a header, you get a separate copy in each cpp file you include it in. 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 at file scope 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 as it will always have the same value anyway.

like image 45
Bo Persson Avatar answered Sep 21 '22 15:09

Bo Persson