创建一个全局ofstream变量

C++: Making a global ofstream variable

本文关键字:全局 ofstream 变量 一个 创建      更新时间:2023-10-16

我想在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文件,所以我不认为适当的链接是问题。

您还没有在任何地方定义outputfileextern std::ofstream outputfile;行声明了变量,但实际上并没有为它定义存储空间。在main.cppcalculate.cpp

中需要以下行
std::ofstream outputfile;