如果变量在 .h 文件中定义为"static "怎么办?

What If a variable is defined as "static " in .h file?

本文关键字:static 怎么办 定义 变量 文件 如果      更新时间:2023-10-16

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的"字符串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文件中,我为hh.h编写了一个防御语句,以保护它不被多次包含(我使用-E选项来检查预编译文件)。然后,如果hh.h不会在最终对象文件中包含两次以上,为什么链接器可以多次访问头文件中解密的全局变量(如m)?这是我的第一个问题。

另一方面,如果我将m声明为staic,这意味着只有那些包含声明m的头文件的人才会使用m。但我希望变量m可以作为全局变量共享。这是我的第二个问题。

如果我的想法中有任何错误的理解,请指出。谢谢

在头文件中将变量声明为static与在包含该头的每个文件中将变量宣布为static具有完全相同的效果。每个翻译单元(即.cpp文件)最终都会有自己的变量实例,与其他翻译单元中的实例不同。这是令人难以置信的困惑,几乎可以肯定不是你想要的。不要这么做。