Michał Michał - 9 months ago 87
C Question

Static const variable declaration in a header file

If I declare static const variable in header file like this:

static const int my_variable = 1;

and then include this header in more than one
files, will compilator make new instance per each file or will be "smart" enough to see it is
and will make only one instance for all the files?

I know I can make it extern and define it in one of
files that include this header but this is what I am trying not to do.


I answered this at length here. That answer is for C++, but it holds true for C as well.

The translation unit is the individual source file. Each translation unit including your header will "see" a static const int. The static, in this context, means the scope of my_variable is limited to the translation unit. So you end up with a separate my_variable for each translation unit (".c file").

The compiler would not be "smart" to create only one instance for all files, it would be faulty, because you explicitly told it not to do so (static).