类编译中的静态结构C++11,为什么不链接?
C++11 static struct in class compiles, why won't it link?
我想提供多个对象的一次性配置。
这个代码:class Foo
{
public:
static struct Bar {
bool a = true;
int b = 69;
} bar;
};
int main(int argc, char **argv)
{
Foo::bar.a = false;
}
可以正常编译:
$ g++ -c -std=gnu++11 main.cpp
但是链接器抱怨缺少符号:
$ g++ main.o
Undefined symbols for architecture x86_64:
"Foo::bar", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
为什么这个不行?
和
实现同样的事情有什么更好的方法?
该变量仅在类定义内声明,因此您需要对该静态变量(单一)定义,就像对任何其他静态变量一样:
Foo::Bar Foo::bar;
现场演示。请记住,在整个二进制文件中(无论是库还是可执行文件)只能有一个这样的定义,所以这个定义不能出现在可以从几个翻译单元()中包含的头文件中。
相关文章:
- CMake 不链接 C 和 C++ 静态库(未定义对函数的引用)
- std::to_chars在MacOS/clang上编译但不链接
- 为什么即使链接器找到目标文件,我的程序也看不到函数定义?
- SQLite 在 Windows 上的编译时不链接
- cmake不链接库文件
- 为什么在匿名名称空间中定义的模板时,为什么内部链接错误
- 为什么在链接时搜索使用错误工具集的提升库?
- Gradle cpp 插件不链接共享库
- 为什么G 不链接静态程序
- GHC 不链接依赖项
- Cmake 在构建 sfml 时不链接
- 为什么动态链接的二进制显示硬编码为so name
- 代码中的MinGW::块不链接静态OpenSSL库
- 为什么更改链接顺序可以修复一个系统上的一些链接错误?
- 为什么 g++ 链接器不警告这种不一致的函数声明?
- 为什么要链接多个目标文件,而不是一个大的目标文件
- 为什么gcc链接器看不到我的析构函数
- 类编译中的静态结构C++11,为什么不链接?
- 无法理解为什么XCode链接器看不到某些方法
- 为什么收到链接错误,如果不使用内联