Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c++ - Static variable in a Header File

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 includes file1.h and file.h, and each of the two headers defines its own Var1.

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 include var1.h from both file1.h and file2.h, not forgetting the #include guard in var1.h.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...