Here you'll find the following statements under Which header ? :
Finally,
<iostream>
provides the eight standard global objects (cin, cout, etc). To do this correctly, this header also provides the contents of the<istream>
and<ostream>
headers, but nothing else. The contents of this header look like
#include <ostream>
#include <istream>
namespace std
{
extern istream cin;
extern ostream cout;
....
// this is explained below
static ios_base::Init __foo; // not its real name
}
Now, the runtime penalty mentioned previously: the global objects must be initialized before any of your own code uses them; this is guaranteed by the standard. Like any other global object, they must be initialized once and only once. This is typically done with a construct like the one above, and the nested class ios_base::Init is specified in the standard for just this reason.
How does it work? Because the header is included before any of your code, the __foo object is constructed before any of your objects. (Global objects are built in the order in which they are declared, and destroyed in reverse order.) The first time the constructor runs, the eight stream objects are set up.
My question: when I include the header file <iostream>
in several .cpp
files, how does the scheme above guarantees that there will be just one definition for the objects cin
, cout
, etc... ?