默认情况下,const 变量是文件的本地变量

const variable Are Local to a File By Default

本文关键字:变量 文件 const 默认 情况下      更新时间:2023-10-16

在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;

在您无法修改的全局范围内。如果您所说的"文件本地"是指内部链接,那么是的,这是正确的。