类编译中的静态结构C++11,为什么不链接?

C++11 static struct in class compiles, why won't it link?

本文关键字:为什么不 链接 C++11 结构 编译 静态      更新时间:2023-10-16

我想提供多个对象的一次性配置。

这个代码:

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;

现场演示。请记住,在整个二进制文件中(无论是库还是可执行文件)只能有一个这样的定义,所以这个定义不能出现在可以从几个翻译单元()中包含的头文件中。