static vs non-static variables in namespace(命名空间中的静态变量与非静态变量)
问题描述
我有一个命名空间 foo,其中包含一个整数 bar,声明为...
I have a namespace foo which contains an integer bar, declared so...
foo.h:
namespace foo {
int bar;
}
现在,如果我只在一个文件中包含 foo.h,这工作得很好.但是当我从两个或多个文件中包含 foo.h 时出现问题:我收到链接器错误.我发现如果我将 bar 声明为 static,我可以在多个文件中包含 foo.h.这对我来说似乎很奇怪,因为我不知道可以在命名空间内声明一个静态变量.(这到底是什么意思?)
Now if I include foo.h in only one file, this works just fine. But a problem arises when I include foo.h from two or more files: I get a linker error. I figured out that if I declare bar as static, I can include foo.h in more than one file. This seems strange to me, because I wasn't aware that one could declare a static variable inside of a namespace. (what does that even mean?)
为什么会这样?更重要的是,为什么没有它没有static就不能工作?static 在 namespace 中使用时是什么意思?
Why does this work? And more importantly, why doesn't it work without static? What does static mean when used in a namespace?
推荐答案
static 在不同的上下文中有多种含义.在此特定上下文中,这意味着变量具有内部链接,因此包含该标头的每个翻译单元都将拥有自己的变量副本.
There are multiple meanings for static in different contexts. In this particular context it means that the variable has internal linkage, and thus each translation unit that includes that header will have it's own copy of the variable.
请注意,虽然这将使链接器错误静音,但它会为生成的每个目标文件维护一个单独的 foo::bar 变量(更改将不会在不同的目标文件中可见)).
Note that while this will silent the linker error, it will do so maintaining a separate foo::bar variable for each one of the object files generated (changes will not be visible across different object files).
如果您需要一个变量,您应该在标题中将其声明为 extern 并在一个翻译单元中提供一个定义.
If you want a single variable, you should declare it as extern in the header and provide a single definition in one translation unit.
这篇关于命名空间中的静态变量与非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:命名空间中的静态变量与非静态变量
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
