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

标签 c++ enums linker-errors

我在为我的游戏设置状态系统时遇到了关于枚举的问题。我想要做的是定义 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;
    }
}

关于c++ - 如何在 C++ 中的不同翻译单元之间共享枚举实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551215/

相关文章:

c++ - 从用户控制的内存池分配和实例化对象

swift - 在 swift iOS 中出现意外值时,如何将 nil 设置为可编码枚举

c++ - QT Creator 的 LNK4099 链接器警告

c++ - 带cmake的 Armadillo 链接器错误

c++ - 错误 LNK2019 : unresolved external symbol NvAPI_GPU_GetThermalSettings referenced in

c++ - 链接错误 : collect2: error: ld returned 1 exit status

c++ - 当 QDialogs show() 时保持 QMainWindow 最小化

java - 为什么 Enum 被认为比常量更类型安全?

c++ - cocos2d-x标签文本字符间距

c++ - 不同编译器的枚举大小(以字节为单位)