Static variable in the header file

A static variable has a file size. Say I have the following two files:

  • file1.h
  • file1.cpp
  • file2.h
  • file2.cpp

I declared a static variable say static int Var1 in both header files. Both file1.h and file2.h are included in the main.cpp file.

I did this because the static variable will have a file area, so it will not conflict with each other. But after compilation, I found that it shows a conflict.

Now the static variable behaves like an extern variable. On the other hand, if I declare a static variable in both .cpp files, it compiles well.

I can not understand this behavior.

Can any body explain how area and communication work in this scenario.

+7
source share
3 answers

Static variables are local to the compilation unit. The compilation unit is basically a .cpp file with the contents of the .h file inserted instead of each #include directive.

Now in the compilation block you cannot have two global variables with the same name. This is what happens in your case: main.cpp includes file1.h and file.h , and each of the two headers defines its own Var1 .

If logically these are two different variables, give them different names (or put them in different namespaces).

If this is the same variable, move it to a separate header file var1.h and include var1.h from file1.h and file2.h , remembering to # enable protection in var1.h

+13
source

Static variables have a translation unit scope (usually a .c or .cpp file), but the #include directive simply copies the text of the file verbatim and does not create another translation unit. After pre-processing, this is:

 #include "file1.h" #include "file2.h" 

Goes to the following:

 /* file1.h contents */ static int Var1; /* file2.h contents */ static int Var1; 

Which, as you know, is invalid.

+8
source

Assuming the static variable static int Var1 is globally in both headers and includes both headers in main.cpp . Now, first, the pre-processor copies the contents of the included files to main.cpp . Since there is Var1 declared in main.cpp that is declared twice in the same scope, a declaration error occurs. (i.e. one is copied from file1.h and the other form is file2.h using a preprocessor)

Each source file is compiled separately. Now, when you declare separately in your source files, each source file does not know about the existence of another static variable present in another source file with the same name. Thus, the compiler does not report an error. You can mark it as extern if you want the variable to be shared between the source files.

+2
source

All Articles