I have a header file that I include into my main.cpp file. I want to set some flags when this file is included.


I want to set that automatically how can I do this? I tried:


//Gives me the error:
//error: 'cout' in namespace 'std' does not name a type|

Or better yet, how can I enable that for all streams automatically?

Edited by triumphost

4 Years
Discussion Span
Last Post by mike_2000_17

It is generally not recommended to do this at all. There is always the danger of the static initialization order fiasco. I'm not sure how safe it is to do this for a standard component like cout.

The safest thing is to just define a function that will perform this task, and you can make that function for all stream types, like so:

void init_stream_flags(std::ios_base& str) {

But, then, of course, that function has to be called either in main() or elsewhere on all streams that you will be using.

If you wanted to actually get the behavior you described (static initialization) for cout, you would need to wrap the functionality inside a class constructor, and construct a static object of that class. As so:

class stream_initializer {
    stream_initializer() {

static const stream_initializer str_init_object = stream_initializer();

The construction of the stream initializer will call the init_stream_flags on std::cout. Of course, that assumes that std::cout itself has already been initialized, which is not guaranteed, and thus, not a safe assumption to make.


Ahh that seems like a headache. Uh what could happen if it's not initalized and I do assume? Though I will not, I just want to know.


Uh what could happen if it's not initalized and I do assume?

Anything can happen, it is undefined behavior. The more likely outcomes are that nothing happens (and your flag setup is inaffective), or that your program crashes before it even starts executing the main() function.

Whether cout will be initialized at the point where you set the flags depends on the compiler, the platform and the order in which the linker decides to arrange things. Quite unpredictable.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.