C++全局常量声明和定义extern

it2024-06-19  43

问题描述:

在一个源文件A.cpp中声明了一个全局常量,在源文件B.cpp中定义了该全局常量,结果在A.cpp中使用全局常量报错了,错误如下:

error LNK2001: 无法解析的外部符号 “int const g_iCount” (?g_iCount@@3HB) fatal error LNK1120: 1 个无法解析的外部命令

A.cpp源码如下:

#include <iostream> using namespace std; extern const int g_iCount; int main() { cout << g_iCount << endl; return 0; }

B.cpp 源码如下:

const int g_iCount = 100;

原因分析:

该错误明显是因为程序使用了未定义的变量而报的错,但是B.cpp有定义该全局常量量;尝试把const去掉,编译正常,应该问题出在const修饰上面。


解决方案:

因为常量默认只能在当前文件中使用,其他文件是用不了的,必须加上一个关键字extern,代码如下:

extern const int g_iCount = 100;

加上关键字extern,重新编译,通过

最新回复(0)