15

静态变量具有文件范围。假设我有以下两个文件:

  • 文件1.h
  • 文件1.cpp
  • 文件2.h
  • 文件2.cpp

我已经static int Var1在两个头文件中声明了静态变量。两者file1.hfile2.h包含在main.cpp文件中。

我这样做是因为静态变量将具有文件范围,因此不会相互冲突。但编译后我发现它显示冲突。

现在静态变量的行为就像一个extern变量。另一方面,如果我在两个 .cpp 文件中声明静态变量,它编译得很好。

我无法理解这种行为。

任何机构都可以解释范围和链接在这种情况下是如何工作的。

4

3 回答 3

21

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.

于 2011-02-18T11:11:59.257 回答
13

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

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

Will turn into this:

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

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

Which, as you know, is invalid.

于 2011-02-18T11:17:37.157 回答
3

Assuming static variable static int Var1 is at global scope in both the headers and included both the headers in main.cpp. Now, first the pre-processor copies the content of included files to the main.cpp. Since, at main.cpp there is Var1 declared twice at the same scope, multiple declaration error will arise. ( i.e, one copied from file1.h and the other form file2.h by the pre-processor)

Each source file is compiled individually. Now, when you declare seperately in their source files, each source file is unaware of existence of the other static variable present in the other source file bearing the same name. So, compiler don't report an error. You can mark it as extern, if you want a variable to be shared among the source files.

于 2011-02-18T11:17:03.013 回答