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

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

本文关键字:单元 之间 共享 实例 枚举 翻译 C++      更新时间:2023-10-16

我正在为我的游戏设置一个状态系统,遇到了一个关于枚举的问题。我正在尝试定义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;
}
}