Windows 8,Clang
hh.h文件:
#ifndef _H_
#define _H_
#include<string>
using std::string;
static string m; // If m is defined as static, the promble of multiple definitions will be solved.
#endif
foo.cpp
#include "hh.h"
int foo()
{
m = "456";
}
bar.cpp
#include "hh.h"
int main()
{
m = "123";
}
使用-c选项编译foo.cpp和bar.cpp
然后,我使用“nm”命令检查导出符号表
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 d .eh_frame
00000000 r .rdata
00000000 t .text
00000000 b m // a local var, as 'b'
// others
否则,如果我没有使用static限定符来定义"string m",比如在hh.h文件中:
#ifndef _H_
#define _H_
#include<string>
using std::string;
string m;
#endif
而且,我使用“nm”命令来检查导出符号表。
00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 d .eh_frame
00000000 r .rdata
00000000 t .text
00000000 B m // a global var, as 'B'
// others
链接器报告变量 m 有“重复定义”的问题。
我的想法是,在 hh.h 文件中,我编写了一条防御性语句来保护它不被多次包含(我使用 -E 选项检查了预编译文件)。那么,如果在最终的目标文件中,hh.h 不会被包含两次以上,为什么在头文件中声明的全局变量(如 m)可以被链接器重复访问?这是我的第一个问题。
另一方面,如果我将 m 声明为 static,这意味着只有包含了m声明的头文件的人才能使用m。但我希望变量 m 可以作为全局变量共享。这是我的第二个问题。
如果我的想法有任何误解,请指出,谢谢!
_H_
)以及包含两个连续下划线的名称保留供实现使用。请勿在您的代码中使用它们。 - Pete Becker