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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…