using outFile with other cpp file in same program

closed account (NCRLwA7f)
I have been looking online for some help on how to write to a file from multiple cpp files in a single project but no luck. I have used cout on multiple cpp files with no problem so for example:
using cout in the main cpp is straightforward just use cout <<
in a secondary cpp I can use std::cout <<
This does not work with outFile, I cannot use std::outFile <<

How can I fix this? Do I need to include #include <fstream> on my secondary cpp? or ofstream outFile;
Thank you in advanced.
Last edited on
Hello DaRealFonz,

Let me say that if you know the difference between "cout" and "std::cout" then stick with "sdt::cout", "std::cin", std::endl", "std::ofstream" and "std::ifstream" along with the others that you should learn. Using the line using namespace std; WILL get you in trouble some day. If you have to use "std::cout" in a separate .cpp file there is a chance you did not include <iostream> at the top of the program.

For "outFile" you have two choices when using this in separate .cpp files in a project. First you could open the stream in the file and close when finished or open the stream in main and pass "outFile" to the functions that need it. The function call would be Foo(outFile); and the function definition would be Foo(std::ofstream& outFile). This would be passing the stream by reference which is needed.

And yes. Every .cpp file need all the include files that you have put in the main file and sometimes others that do not need to be in main. It depends on what the function is going to do.

Before the project is compiled think of each .cpp file as a stand alone program needing all the include files and header files, that you have written, to make it work. When the project is compiled only one of every duplicate include file is put in the program. Although header files that you write could easily be included twice if you are not careful.

Hope that helps,

Andy
Topic archived. No new replies allowed.