Static variable has file scope. Say I have two following files:
I have declared static variable say static int Var1
in both the header files. Both file1.h
and file2.h
are included in main.cpp
file.
I did this since the static variable will have file scope so it won't conflict each other. But after compilation I found it is showing conflict.
Now static variable is behaving like a extern
variable. On the other hand if I declare the static variable in both .cpp files, it compiles well.
I am unable to understand this behavior.
Can any body explain how scope and linkage are working in this scenario.
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.
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.
Basically, each source file together with all included header files is a single translation unit. So If you have a static variable in a header file then it will be unique in each source file (translation unit) the header file is included in.
Static variables have the static scope and are defined once and used multiple times. Non-static variables have the dynamic scope and are defined and used each time the variable is needed. Static variables are declared in the header file and non-static variables are declared in the source file.
Static variables have translation unit scope (usually a .c
or .cpp
file), but an #include
directive simply copies the text of a file verbatim, and does not create another translation unit. After preprocessing, this:
#include "file1.h"
#include "file2.h"
Will turn into this:
/* file1.h contents */
static int Var1;
/* file2.h contents */
static int Var1;
Which, as you know, is invalid.
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