如果变量在 .h 文件中定义为"static "怎么办?
What If a variable is defined as "static " in .h file?
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
文件)最终都会有自己的变量实例,与其他翻译单元中的实例不同。这是令人难以置信的困惑,几乎可以肯定不是你想要的。不要这么做。
相关文章:
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 如果我想在没有更新编译器的情况下使用新功能,该怎么办?
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- 这些老式的演员怎么办?
- 如果参数与数据成员的参数同名,该怎么办?
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- MacOS 10.14b / C++使用:找不到命令,该怎么办?
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 如果用户输入在整数变量中浮动怎么办?
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- C++线程"Call to non-static member function without an object argument"
- 如果变量在 .h 文件中定义为"static "怎么办?