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.
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.
A static variable should be declared with in the file where we use it shouldn't be exposed to 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.
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).
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With