头文件中的静态变量 [英] 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
- file1.h
- file1.cpp
- file2.h
- file2.cpp
我已在两个头文件中声明静态变量说 static int Var1
。 file1.h
和 file2.h
都包含在 main.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.
现在静态变量的行为像一个 extern
变量。另一方面,如果我在两个.cpp文件中声明静态变量,它会编译得很好。
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.
我无法理解这个行为。
任何主体都可以解释范围和链接在这种情况下如何工作。
Can any body explain how scope and linkage are working in this scenario.
推荐答案
本地到编译单元。编译单元基本上是 .cpp
文件,其中插入 .h
文件的位置替换每个 #include
指令。
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.
现在,在编译单元中,不能有两个具有相同名称的全局变量。这是你的情况发生了: main.cpp
包括 file1.h
和文件。 h
,并且两个标头中的每一个定义其自己的 Var1
。
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).
如果这些是同一个变量,将它移动到一个单独的头文件 var1.h
,并从 file1.h $ c $中包含
var1.h
c>和 file2.h
,不要忘记 #include guard 在 var1.h
。
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
.
这篇关于头文件中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!