That will work, but I recommend that you don't do that.
First, global variables should be avoided if possible, as they make it harder to understand the flow of data through the program.
Second, C++ encourages the use of RAII for resource management whenever possible. When RAII is used to its full effect, most the lifetime of objects become tied to the program structure. For example, for a file, one might do this:
1 2 3 4 5 6
|
{
std::fstream file(/*parameters*/); //If you pass parameters to the constructor, it will open the file for you.
//Now file is open.
//Use the file normally.
//Don't call close().
} //When the object goes out of scope, the file is closed automatically.
|
This style minimizes programmer errors, because at any point that you can reference the 'file' object you know that the file is open and ready for use. Compare:
1 2 3 4 5 6
|
//'file' declared outside the scope.
{
file.read(/*...*/); //Will this work? Is the file open now?
some_random_function(); //Does this function call open() or close()?
file.write(/*...*/); //Is the file still open? Are we even writing to the same file?
}
|
Try to structure your code so that a) you never explicitly call open() or close() on file streams, and b) pass the std::fstream object to the functions that need it, rather than declaring it in global scope.