考虑以下场景:
我的文件.cpp :
const int myVar = 0; // 全局变量
另一个文件.cpp:
void myFun()
{
std::cout << myVar; // compiler error: Undefined symbol
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我添加extern const int myVar;在AnotherFile.cpp使用前,连接器作为抱怨
未解决的外部
我可以移动的声明myVar,以MyFile.h,包括MyFile.h在AnotherFile.cpp来解决这个问题。但我不想将声明移动到头文件中。有没有其他方法可以使这项工作?
在 C++ 中,const 意味着内部链接。需要声明myVar的extern在MYFILE.CPP:
extern const int myVar = 0;
Run Code Online (Sandbox Code Playgroud)
在 AnotherFile.cpp 中:
extern const int myVar;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1595 次 |
| 最近记录: |