如何在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;
}
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 什么时候调用组成单元对象的析构函数
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 不同翻译单元中不可重载的非内联函数定义
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 是否允许类在程序中的不同翻译单元之间具有不同的定义?
- 如何在C++中的不同翻译单元之间共享枚举的实例
- 在带有单元格数组的C 特征矩阵和MATLAB MXARRAY之间传递数据
- 编译单元之间共享的全局常量对象
- 如何知道数组中两点之间的单元格数
- Visual Studio C++托管测试项目和本机单元测试项目之间的区别
- 忽略两个C++宏之间的代码(防止创建静态单元测试对象)
- 在确保翻译单元之间的可用性时,不赞成使用静态
- 二维矩阵中两个单元格之间的距离