默认情况下,const 变量是文件的本地变量
const variable Are Local to a File By Default
在C++入门(第4版)中,有一节如下:
与其他变量不同,除非另有说明,否则在全局范围内声明const
变量是定义对象的文件的本地。变量仅存在于该文件中,不能由其他文件访问。我们可以通过指定const
对象来在整个程序中访问它extern
:
// file_1.cc
// defines and initializes a const that is accessible to other files
extern const int bufSize = fcn();
// file_2.cc
extern const int bufSize; // uses bufSize from file_1
// uses bufSize defined in file_1
for (int index = 0; index != bufSize; ++index)
// ...
这是我尝试过的:
// file_1.cc
// defines and initializes a const that is accessible to other files
const int bufSize = fcn();
// file_2.cc
extern const int bufSize; // uses bufSize from file_1
// uses bufSize defined in file_1
for (int index = 0; index != bufSize; ++index)
// ...
它也没有问题。所以我的问题是:
const
变量是文件的本地变量,还是这只是一个错误?
非常感谢。
在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在C++中,常量值默认为内部链接,这允许它们出现在头文件中。
在 C 源代码文件中将变量声明为 const 时,可以按如下方式声明
:const int i = 2;
然后,您可以在另一个模块中使用此变量,如下所示:
extern const int i;
但是要在 C++ 中获得相同的行为,您必须将 const 变量声明为:
extern const int i = 2;
如果您希望在 C++ 源代码文件中声明一个 extern 变量以在 C 源代码文件中使用,请使用:
extern "C" const int x=10;
以防止C++编译器进行名称重整。
参考: http://msdn.microsoft.com/en-us/library/357syhfh%28v=vs.71%29.aspx
extern
只是一个声明,无论变量是否const
。
不过,const
意味着内部联系。你可以把它想象成一个
static int x;
在您无法修改的全局范围内。如果您所说的"文件本地"是指内部链接,那么是的,这是正确的。
相关文章:
- 通过多个头文件使用常量变量
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 无法通过头文件保存变量的值
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在 C++ 中将双精度变量写入二进制文件
- 如何使用文件中的文本,例如变量
- 定义C++新的环境变量并在 bat 文件中使用它
- 在头文件中定义变量不会出错
- 复制文件流C++静态变量
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- C++将文本从.txt文件解析为变量
- 从 C 中的变量获取文件的路径,C++
- 可以在 cpp 文件中C++定义为特殊符号的变量β
- 如何使用可视化代码和平台IO将环境变量注入CPP文件?
- C++ 静态成员变量 - 文件之间的访问
- 正在创建一个集中式变量文件
- 静态成员变量文件作用域