1

I want to open an output file in main.cpp, then write to it in another file calculate.cpp.

main.cpp:

#include main.hpp

using namespace std;

int main() {
    outputfile.open("output.txt");
}

using the global variable from the header file main.hpp

extern std::ofstream outputfile;

Then write to it in another file calculate.cpp

#include main.hpp

void calculate() {
    outputfile << "write this to the external file" << endl;
}

When I do this, I get the error

undefined reference to 'outputfile' in main.cpp
undefined reference to 'outputfile' in calculate.cpp

I'm working on a large code that has a premade make file, so I don't think proper linking is the issue.

gevorg
  • 4,835
  • 4
  • 35
  • 52
Peter
  • 367
  • 1
  • 4
  • 12

1 Answers1

2

You haven't defined outputfile anywhere. The line extern std::ofstream outputfile; declares the variable, but nothing actually defines storage for it. You need the following line in either main.cpp or calculate.cpp

std::ofstream outputfile;
Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
  • `Clang-Tidy: Initialization of 'outputfile' with static storage duration may throw an exception that cannot be caught` – Alexis Aug 11 '21 at 03:57