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