Michał Michał - 1 year ago 169
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download