访问另一个.cpp文件中的.cpp文件中定义的全局变量
Accessing a global variable defined in a .cpp file in another .cpp file
考虑以下方案:
myfile.cpp :
const int myVar = 0;
//全局变量
另一个file.cpp :
void myFun()
{
std::cout << myVar; // compiler error: Undefined symbol
}
现在,如果我在 emotefile.cpp中添加 未解决的外部 我可以将 extern const int myVar;
myVar
的声明移至 myfile.h ,并include myfile.h in eme> ernefile.cpp 以解决问题。但是我不想将声明移至标题文件。还有其他方法可以做这项工作吗?
在C 中,const
意味着内部链接。您需要在myfile.cpp中将 myVar
声明为 extern
:
extern const int myVar = 0;
在另一个file.cpp中:
extern const int myVar;
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 命名空间中具有.h和.cpp文件的类
- 为什么我的主文件.cpp不打印头文件中的任何内容
- 生成文件错误 - 找不到文件 - *.cpp
- 如何在文件.cpp gtkmm中声明小部件
- 没有实现文件(.cpp)的派生类
- 如何使用"CMakeLists.txt"中的add_library将整个文件(.cpp,.h等)包含在目录中
- 如何在Linux / Windows操作系统上使用文件*.cpp一步编译下面的代码
- 关于 Linux .so 文件无法链接到主文件.cpp文件
- 文件.cpp从Windows到Linux
- Ubuntu C++ 编译器错误: g++: 错误: 文件.cpp: 没有这样的文件或目录
- 如何将文件.cpp编译为本机编译
- 使用模板类时,似乎无法包含除 main 以外的任何 cpp 文件.cpp
- 无法编译C++文件.cpp。C++98模式
- 为什么C++头文件不需要包含实现文件 (.cpp)
- 如何访问位于独立文件(.cpp)中的非成员函数
- 如何在Visual Studio Code中通过键盘快捷键切换头文件/cpp文件
- 如何将数据从stringstream写入文件(CPP)
- 为什么filestream不把空白写入文件cpp ?