创建一个全局ofstream变量
C++: Making a global ofstream variable
我想在main.cpp
中打开一个输出文件,然后在另一个文件calculate.cpp
中写入它。
main.cpp :
#include main.hpp
using namespace std;
int main() {
outputfile.open("output.txt");
}
使用头文件main.hpp
中的全局变量
extern std::ofstream outputfile;
然后写入另一个文件calculate.cpp
#include main.hpp
void calculate() {
outputfile << "write this to the external file" << endl;
}
当我这样做时,我得到错误
undefined reference to 'outputfile' in main.cpp
undefined reference to 'outputfile' in calculate.cpp
我正在研究一个大型代码,有一个预制的make文件,所以我不认为适当的链接是问题。
您还没有在任何地方定义outputfile
。extern std::ofstream outputfile;
行声明了变量,但实际上并没有为它定义存储空间。在main.cpp
或calculate.cpp
std::ofstream outputfile;
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何创建一个空的全局类并在启动时实例化它
- 内联函数中具有内部链接的全局变量
- 为什么虚函数不能是静态的和全局的?
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局作用域中函数指针的赋值
- g++用户定义的动态链接库上的全局new和delete运算符
- 在命名空间中使用全局命名空间中的函数
- 全局变量 多读取器 一个写入器多线程安全?
- 类的全局对象和静态成员
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- 如何使用 llvm-10 库在C++定义 LLVM 全局值变量?
- 使用全局声明的向量时,C++双重释放错误/损坏
- std::ofstream 作为类成员删除复制构造函数?
- 创建一个全局ofstream变量