outFile declaration

I am working with multiple files that each have functions with 'cout' statements which I have changed to outFile. Can I declare outFile globally in main and have 'extern' in all of the other files that use it? If so what's the syntax for it because I'm at a loss!

Thanks!!
Last edited on
Can I declare outFile globally in main and have 'extern' in all of the other files that use it?
You can define a ofstream outFile in the global space like:
1
2
3
4
5
6
7
8
9
10
// main.cpp
#include <fstream>
std::ofstream outFile;
bool foo();
int main()
{
   // etc...
   std::cout << "Is open: " << foo() << std::endl;
   return 0;
}
1
2
3
4
5
6
// other.cpp
#include <fstream>
extern std::ofstream outFile;
bool foo() {
  return outFile.is_open(); 
}
$ g++ main.cpp other.cpp 
$ ./a.out
Is open: 0


Note: If you can try to not use globals.
Last edited on
Topic archived. No new replies allowed.