Static variable has file scope. Say I have two following files:
- file1.h
- file1.cpp
- file2.h
- file2.cpp
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.
Static variables are local to the compilation unit. A compilation unit is basically a
.cpp
file with the contents of the.h
file inserted in place of each#include
directive.Now, in a compilation unit you can't have two global variables with the same name. This is what's happening in your case:
main.cpp
includesfile1.h
andfile.h
, and each of the two headers defines its ownVar1
.If logically these are two distinct variables, give them different names (or put them in different namespaces).
If these are the same variable, move it into a separate header file,
var1.h
, and includevar1.h
from bothfile1.h
andfile2.h
, not forgetting the #include guard invar1.h
.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:Will turn into this:
Which, as you know, is invalid.
Assuming static variable
static int Var1
is at global scope in both the headers and included both the headers inmain.cpp
. Now, first the pre-processor copies the content of included files to themain.cpp
. Since, atmain.cpp
there isVar1
declared twice at the same scope, multiple declaration error will arise. ( i.e, one copied fromfile1.h
and the other formfile2.h
by the pre-processor)Each source file is compiled individually. Now, when you declare seperately in their source files, each source file is unaware of existence of the other static variable present in the other source file bearing the same name. So, compiler don't report an error. You can mark it as extern, if you want a variable to be shared among the source files.