Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static const variable declaration in a header file

Tags:

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 .c files, will compilator make new instance per each file or will be "smart" enough to see it is const and will make only one instance for all the files?

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

like image 978
Michał Avatar asked Aug 12 '16 07:08

Michał


People also ask

Can static variables be declared in a header file?

Yes there is difference between declaring a static variable as global and local. If it is local, it can be accessed only in the function where it's declared. But if it is global, all functions can access it.

Should static variables be in header?

A static variable should be declared with in the file where we use it shouldn't be exposed to header file.

Can you declare variables in a header file?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.

How do you define a constant in a header file?

You need to do: to make a constant pointer, so that the rule will apply to it. Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int . I also put the * next to the variable: i.e. int *ptr; instead of int* ptr; (compare also this discussion).


1 Answers

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

like image 154
DevSolar Avatar answered Oct 17 '22 16:10

DevSolar