c++ - Static variable in a Header File -
static variable has file scope. have 2 following files:
- file1.h
- file1.cpp
- file2.h
- file2.cpp
i have declared static variable static int var1
in both header files. both file1.h
, file2.h
included in main.cpp
file.
i did since static variable have file scope won't conflict each other. after compilation found showing conflict.
now static variable behaving extern
variable. on other hand if declare static variable in both .cpp files, compiles well.
i unable understand behavior.
can body explain how scope , linkage working in scenario.
static variables local compilation unit. compilation unit .cpp
file contents of .h
file inserted in place of each #include
directive.
now, in compilation unit can't have 2 global variables same name. what's happening in case: main.cpp
includes file1.h
, file.h
, , each of 2 headers defines own var1
.
if logically these 2 distinct variables, give them different names (or put them in different namespaces).
if these same variable, move separate header file, var1.h
, , include var1.h
both file1.h
, file2.h
, not forgetting #include guard in var1.h
.
Comments
Post a Comment