这里需要extern关键字,cpp文件中的const

Is extern keyword required here, const in cpp file

本文关键字:文件 const cpp extern 关键字 这里      更新时间:2023-10-16

如果头文件中有

namespace Bob
{
    extern const T x;
};

在源文件

extern const T Bob::x = 123;

源文件中的第二个extern是必需的还是可选的?

我已经搜索并发现了相互矛盾的信息。

从这个网页:http://msdn.microsoft.com/en-us/library/357syhfh.aspx

但是要在c++中获得相同的行为,您必须将const变量[在源文件]声明为:

extern const int i = 2;

通常,extern关键字告诉编译器不要定义一个符号,因为它将在其他地方定义。例如:

namespace Bob {
    extern T x;
}

没有定义变量x,而是声明它。您可以拥有任意多的extern声明。但是,如果不提供定义,则链接将失败。所以你必须定义

T Bob::x;

在代码的某个地方,以便提供定义。

const关键字在这里有点特殊,因为它暗示了内部链接。这意味着,x的定义在定义它的特定编译单元之外是不可见的。要更改此行为,您需要写入

    extern const T Bob::x = 123;

如果您希望xconst,并且从其他编译单元引用它。

----再编辑----
我要明确一点:如果const变量应该在其编译单元之外被引用,那么必须显式地声明它为extern

但是,如果声明与定义分开给出,则定义不一定需要再次指定关键字extern。另一个演示示例:

myheader.h

extern const int i;

声明i为具有外部链接的const整数,但没有定义它。

main.cpp, version 1

#include "myheader.h" //Through the include, the above declaration of `i` comes before its definition.
const int i=123; // Although the `extern` modifier is omitted here,
                 // it's still in effect because we already declared `i` as `extern`
                 // Therefore it makes no difference here, whether or not you specify `extern` again.
                 // The compiler knows this is a definition either way, because of the initialization.

main.cpp, version 2

//#include "myheader.h"
extern const int i=123; // this line is declaration and definition in one, because we did not include
                        // the declaration from myheader.h. Thus, to tell the compiler that you want
                        // `i` with external linkage, you MUST specify `extern`. Otherwise you'll get
                        // internal linkage.

我希望现在所有这些对你来说都是有意义的。

可以使用staticextern关键字控制符号的链接。在命名空间范围内,非const符号的默认链接是extern, const符号的默认链接是static(即内部链接)。这对c++有效,但对C无效(在C中,你必须将其声明为static以使其具有内部链接)。

所以如果你有

const int i = 2;

放到一个。c文件中,你可以通过声明

将它放到另一个单元中
extern const int i;

在C中很好,因为该变量默认具有外部链接(使用extern关键字,您可以指示编译器在另一个单元中找到它),但在c++中相同的

const int i = 2;

放到。cpp文件中(坚持我写的)有内部链接,必须用

来定义。
extern const int i = 2;

显式地具有外部链接,并且能够与

一起用于另一个单元
extern const int i;

最后,当你初始化一个全局变量时,你总是在中定义它,这意味着以下内容是完全有效的:

#include <iostream>
using namespace std;
#define T int
extern const T x; // This is a declaration
extern const T x = 123; // This is a definition
int main() {
  std::cout << x; // 123
  return 0;
}

这意味着第二个'extern'关键字也是不必要的。