Static const variable declaration in header file

If I declare a static constant variable in the header file as follows:

static const int my_variable = 1; 

and then include this header in more than one .c file, will the compiler make a new instance for each file or will it be smart enough to see that it is const and make only one instance for all files?

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

+8
c header-files compilation
source share
3 answers

I answered it here . This answer is for C ++, but it is valid for C.

A translation unit is a separate source file. Each translation unit, including your title, will “see” static const int . static in this context means that my_variable limited to translation unit. Thus, you get a separate my_variable for each translation unit (" .c file").

The compiler will not be smart to create only one instance for all files, this would be a mistake because you explicitly told it not to do this ( static ).

+9
source share

If you use the address of this object - the compiler certainly creates one instance for each translation unit. If you use only the value - it is probably smart enough not to create an object at all - the value will be included if necessary.

+3
source share

I assume that it will make only one instance for all files. But you can check it by calling it in different files and check its value

-one
source share

All Articles