c++ - extern const 在这种特殊情况下

标签 c++ extern

关于在 C++ 中使用 externconst 还有其他问题。我也读过内部和外部链接(自从我使用 C++ 以来已经有一段时间了)但是如果有人提醒我以下特定情况的用法,我将不胜感激。

我有两个 cpp 文件:Description.cpp 和 Register.cpp 以及一个 hpp 文件:Description. h .他们是这样的

//Description.cpp
#include "Description.hpp"
extern const FD models[];
//some other code

.

//Register.cpp
#include "Description.hpp"
extern const FD models[2]={
                           {"elementA",{1,2}},
                           {"elementB",{3,4}}
                          };

.

//Description.hpp
struct FD{
  string name;
  double v[2];
};

我想知道为什么在 Register.cpp 中 extern 关键字是必需的

最佳答案

如评论中所述,默认情况下,const 对象具有 internal linkage ,这意味着您只能从您定义它的文件中看到它。要更改它,您可以使用关键字 extern,这意味着“可以从其他文件中看到该变量”。因此,在 Register.cpp 中,您需要 extern 来告诉链接器使其在其他地方可见,而在 Description.cpp 中,您需要 extern 告诉编译器它可能在别处定义。

更好的解决方案是将声明 extern const FD models[]; 移动到 .hpp 文件(Description.hpp或新的 Register.hpp,具体取决于项目的详细信息)。然后在 Description.cpp 和任何其他使用 models 的代码中,您包含该文件并且根本不需要声明。在 Register.cpp 中,您还包含此 header 。然后编译器知道 models 有外部链接,你不需要再说 extern 了。

关于c++ - extern const 在这种特殊情况下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51434418/

相关文章:

c++ - 在 C/C++ 预处理器中单独一行的单个井号/井号 (#) 的目的是什么?

c++ - scoped_lock 访问资源的优雅模式?

c++ - 无法编辑外部变量

c++ - C++中如何通过 "global"获取一个 `extern`类对象

c++ - 如何使用extern类?

c - 函数修改外部变量

c++ - 类成员重载方法的 SFINAE

c++ - 基于uniform int在GLSL中声明数组

C:常量结构数组中的外部常量整数

c++ - 查找数组中数组元素的重复出现?