c++ - 这里是否需要extern关键字,cpp文件中的const

标签 c++

如果我在头文件中

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 整数,但没有定义它。

ma​​in.cpp,版本 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.

ma​​in.cpp,版本 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.

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

关于c++ - 这里是否需要extern关键字,cpp文件中的const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698515/

相关文章:

android - 无法使用 QAndroidJniObject 调用 PowerManager.WakeLock.newWakeLock

c++ - 为什么用整数文字调用重载的 ambig(long) 和 ambig(unsigned long) 会产生歧义?

c++ - 为什么我收到以下错误 : "no match for ' operator= ='" ?(带有模板的嵌套类)

c++ - C++ 是 "waste of time"吗?

c++ - 如何正确删除基类元素

c++ - gdb:tstart 错误 "You can' 的含义 t 当你的目标是 `exec' 时执行此操作“

c++ - 在 CMake 中添加 C++0x 支持

c++ - 我可以在 C++ 中使用 ** vector < pair <int ,vector < int >>> vec** 之类的声明吗?

c++ - 为什么使用 nullPtr 调用函数不会使我的应用程序崩溃?

c++ - 在随机位置生成 QPushButtons 的定时器