Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
accross转换单元访问常量变量 < C++ >代码> const < /> >变量隐式地隐藏在其他翻译单元中。是否可以防止这种情况发生?_C++_Variables_Module_Scope_Constants - Fatal编程技术网

accross转换单元访问常量变量 < C++ >代码> const < /> >变量隐式地隐藏在其他翻译单元中。是否可以防止这种情况发生?

accross转换单元访问常量变量 < C++ >代码> const < /> >变量隐式地隐藏在其他翻译单元中。是否可以防止这种情况发生?,c++,variables,module,scope,constants,C++,Variables,Module,Scope,Constants,是的,在定义前加上externeg extern const int x = 10; 使用extern关键字: extern const int x = 10; // a.cpp extern const int x = 10; // definition // b.cpp extern const int x; // declaration 这将强制变量具有外部链接 对于名称空间范围变量,这通常是默认值,您可以使用静态(或者更好的是,使用匿名名称空间)强制进行内部链接 直到我读

是的,在定义前加上
extern
eg

extern const int x = 10;

使用
extern
关键字:

extern const int x = 10;
// a.cpp
extern const int x = 10; // definition
// b.cpp
extern const int x;      // declaration
这将强制变量具有外部链接

对于名称空间范围变量,这通常是默认值,您可以使用
静态
(或者更好的是,使用匿名名称空间)强制进行内部链接


直到我读了你的问题并尝试了它,我才知道默认情况下名称空间范围
const
变量有内部链接,所以谢谢你。每天学习新的东西

可以通过
extern
关键字来实现:

extern const int x = 10;
// a.cpp
extern const int x = 10; // definition
// b.cpp
extern const int x;      // declaration
这将产生的效果是,如果
a
中的常量值发生变化,您将不需要重新编译
b
,但同时您失去了在
b.cpp
中使用
x
作为编译时常量的能力(即,您将无法编写
int-array[x];

如果没有很强的理由,我宁愿在头文件中定义常量,并将其包含在所有需要它的翻译单元中

// c.h
const int x = 10;
// a.cpp
#include "c.h"
// b.cpp
#include "c.h"

每次更改都必须重新编译依赖于常量的所有转换单元,但您将能够在编译时在所有转换单元中使用它。这种方法的局限性在于,如果您更改常量并只重新编译一些翻译单元,常量的值将不一致(这违反了ODR)。

防止一个具有内部链接,或者默认情况下防止所有转换单元都具有内部链接?@Steve:只有一个。我不想改变语言规则;-)变量链接更有趣:是的,我不知道你为什么要这么做。当然,在头中放一个声明(
extern const int x;
),但是为什么不将定义严格地保留在一个TU中呢?正是因为你给出的理由,顺便说一下。:)