4

在 C++ Primer(第 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文件的本地变量还是只是一个错误?

非常感谢。

4

2 回答 2

3

在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为内部链接,这允许它们出现在头文件中。

在 C 源代码文件中将变量声明为 const 时,您可以这样做:

const int i = 2;

然后,您可以在另一个模块中使用此变量,如下所示:

extern const int i;

但是要在 C++ 中获得相同的行为,您必须将 const 变量声明为:

extern const int i = 2;

如果您希望在 C++ 源代码文件中声明一个外部变量以在 C 源代码文件中使用,请使用:

extern "C" const int x=10;

以防止 C++ 编译器对名称进行修改。

参考:http: //msdn.microsoft.com/en-us/library/357syhfh%28v=vs.71%29.aspx

于 2013-10-25T07:47:15.190 回答
0

extern只是一个声明,无论变量是否const存在。

const意味着内部联系。你可以把它想象成一个

static int x;

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

于 2013-10-25T07:42:31.510 回答