如何在多个源文件中使用静态成员结构?

How to use a static member-struct in multiple source files?

我需要在多个源文件中使用一个结构,它是我 class 的静态成员。这是一个精简的例子:

头文件

namespace NS {
  class Foo {
    public:
    static struct Bar {
      bool test = false;
      uint32_t value; // uninitialized
    } bar; 
  };
}

源文件 1

#include "myHeader.hpp"

using namespace NS;

Foo::Bar Foo::bar;

/* the rest of my first source file */

在我添加第二个源文件之前,这似乎没有任何问题。

源文件 2

#include "myHeader.hpp"

using namespace NS;

Foo::Bar Foo::bar;

/* the rest of my second source file */

将结构添加到第二个源文件后,出现 "multiple definition" 错误。有谁知道如何进行这项工作,以便可以在多个源文件中使用静态成员结构?

单一定义规则也适用于静态数据成员。应该只有 一个 形式的定义

Foo::Bar Foo::bar;

您可以选择将其放入哪个翻译单元(.cpp 文件),但您必须将其放入其中一个

这与 Foo::bar 是否可以在给定的翻译单元中 使用 无关。为此,包含在头文件中的 声明 就足够了。