如何在 C++ 中的不同翻译单元之间共享枚举实例?

How do you share an instance of an enum between different translation units in C++?

我在为我的游戏设置状态系统时遇到了关于枚举的问题。我想要做的是定义 APP_STATE 枚举的一个实例并在不同的翻译单元之间共享它。

代码:

// APP_STATE.h

 #pragma once
 enum class APP_STATE : signed char { RUNNING = 2, LOAD = 1, EXIT = 0, FORCE_QUIT = -1 };

// Source.cpp

#include "APP_STATE.h"
APP_STATE appState = APP_STATE::RUNNING;

// Other.cpp

#include "APP_STATE.h"

namespace other {
    extern APP_STATE appState;

    void foo () {
        appState = APP_STATE::EXIT; // causes a LNK1120 and LNK2001 error, unresolved extrernal symbol
    }
}

您定义了两个个不同的APP_STATE实例:

  • 一个名为::appState:它在全局命名空间中,在APP_STATE.h中声明并在Source.cpp中定义。
  • 另一个名为 other::appState:它在命名空间 other 中,在 Other.cpp 中声明但从未定义,因此出现错误。

Other.cpp 中,您应该将 extern APP_STATE appState; 的声明移到命名空间之外:

// Other.cpp

#include "APP_STATE.h"

extern APP_STATE appState;

namespace other {

    void foo () {
        appState = APP_STATE::EXIT;
    }
}