Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is std::cout defined?

Tags:

c++

std

I would like to know how it works...

In the <iostream> header, there is namespace std:

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;
  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

So, cout is the name of an object of type ostream, and that is defined in another file (due to extern). Ok.

When I tried in my simple program to create an ostream object, I can't, because the constructor of ostream class is protected. Ok.

So, how can I create (define) an object in an extern file, which has a protected constructor, and looks like a global variable?

like image 395
juga92 Avatar asked Oct 30 '25 23:10

juga92


1 Answers

How libstdc++ used by gcc does it:

Storage for cout is defined as a global variable of type fake_ostream which is presumably constructible without problems. https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/globals_io.cc

Then during library initialization rewritten with a placement new using the explicit constructor. https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/ios_init.cc

Other compilers have their own libraries and may use different tricks. Examining the source of libc++ used by clang left as exercise for the reader.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!