这里需要extern关键字,cpp文件中的const
Is extern keyword required here, const in cpp file
如果头文件中有
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;
如果您希望x
是const
,并且从其他编译单元引用它。
----再编辑----
我要明确一点:如果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.
我希望现在所有这些对你来说都是有意义的。
可以使用static
和extern
关键字控制符号的链接。在命名空间范围内,非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'关键字也是不必要的。
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 如何通过头文件中的函数初始化 const int 数组?
- C++ 在头文件或构造函数中初始化 const 类成员变量?
- 将文本文件读取为 const char* 有时有效,有时无效
- 如果在执行过程中替换二进制文件,"const"数组是否驻留在内存中?
- 静态const数据成员在另一个文件中定义
- YAML::LoadFile(std::string const&) 找不到文件 [ROS 中的 yaml-cpp]
- 我可以在类头文件中定义一个类的const静态实例吗
- 在标头文件中使用const
- C++ 中的文件处理错误 - 调用"std::basic_fstream<char, std::char_traits<char> >::open(const char[8],
- 错误:在"boost::文件系统::p ath::文件名() const() + "/""中与"运算符+"不匹配
- 包含多个源文件中包含的"const"的头文件
- 在头文件中声明全局 const 对象
- 默认情况下,const 变量是文件的本地变量
- 为什么在 cpp 文件中定义了非 int const 静态
- 在 MoSync 中将数据写入文件(将 MAUtil::String 转换为 const char*)
- 为什么我可以在多个包含const int的cpp文件中包含一个头文件,而不会出现编译器错误
- 头文件随附的 C++ 文件中的 const 函数
- 头文件中定义的Const float**
- 如何在头文件中定义const-static std::string