静态变量具有文件内部的范围仅在那里它们被被声明,如示于以下代码:静态成员变量文件范围
file1-
static int a;
file2-
extern int a;
这会导致链接错误,因为静态变量a仅在file1中具有范围。但我很困惑与下面的代码:
file2-
#include "file1"
extern int a;
这不会给任何连接错误。那么它意味着编译器引用了在file1中声明的“a”。但是当你调试时,你会发现变量“a”的地址在file1和file2中是不同的。编译器是否在file2中创建另一个全局变量“a”?
完整的代码 -
文件temp1.h -
static int w = 9;
class temp1
{
public:
temp1(void);
public:
~temp1(void);
void func();
};
........................ .. CPP ...............
temp1::temp1(void)
{
int e =w;
}
temp1::~temp1(void)
{
}
void temp1::func()
{
}
............................ ........... file2-
#include "temp1.h"
extern int w;
int _tmain(int argc, _TCHAR* argv[])
{
w = 12;
temp1 obj;
return 0;
}
在这里,当我调试和检查temp1构造函数和file2中的值和adrress是不同的。
除非'temp1.h'包含自身,否则该代码不完整(或可能不正确)。你能显示'temp1.h'的内容吗? – 2011-06-05 14:03:29
发布编辑,我想我的回答完全回答你的问题。在两个翻译单元中,'w'具有_internal linkage_,因为头文件中包含的'w'是'static int w = 9;'声明的第一个声明。这意味着两个翻译单元都有自己独特的独立“w”。 – 2011-06-05 14:35:26
所以这意味着第二个翻译单元也定义变量w,即使它是外部的(因为它不会导致重新定义,因为第一个定义是翻译单元1中的内部连接)? – 2011-06-05 15:13:23