c++ - 外部变量未定义

标签 c++ undefined extern

我遇到了外部变量声明的问题。我有一堆包含结构定义的 .cpp 文件:

const System SystemA = {"A", 1, 2 ...}; //In A.cpp
const System SystemB = {"B", 1, 2 ...}; //In B.cpp
...

这些 Cpp 文件只是作为添加新结构和轻松查找特定结构定义的简单方法提供给服务器。 (因为我可能有 100 个定义,每个定义都是多 [50] 行代码)。

当我尝试在另一个编译单元 (.cpp) 中使用它们时:

extern const System SystemA;
extern const System SystemB;
...

void InitStructs(){
    SystemA.Init();
    SystemB.Init();
    ...
}

我只是得到undefined reference to SystemA undefined reference to SystemB,等等。 我在做这个统一初始化,因为我在每个system.cpp中做的初始化都是静态动态初始化。但这是有风险的,因为无法确保初始化顺序(静态初始化顺序失败)。因此,根据 cpp 编译顺序,我遇到了段错误。

我转向了这种方法,但现在它甚至无法编译.... 有帮助吗?

最佳答案

在 C++ 中,全局范围内的 const 对象默认也是 static,即它们在源文件之外是不可见的。要解决此问题,请将 extern 添加到每个定义中。

关于c++ - 外部变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185401/

相关文章:

c++ - C 与 C++ 中的 typedef 和结构命名空间

undefined - 摩纳哥 registerSignatureHelpProvider() 导致错误 : Cannot read property 'signatures' of undefined

关于外部链接和调用约定的 C++ 标准

c++ - 在 c 结构上调用默认构造函数

C++ fork()——创建 "list"进程

c++ - 使用初始化列表作为函数参数实现 operator[] 的类对象示例

c++ - fcntl 问题编译 C++

java - 构造函数未定义,即使明确导入?

javascript - Node.js request.post 返回未定义

c - 在 C 中重新声明 typedef