Search code examples
clinuxgccoutput-buffering

Flushing stdout messages of c/c++ based executable


My question is general and doesn't relate to a specific debugging scenario.

When a program terminate unexpectedly (panic, memory corruption, access violation etc... ) , sometimes the recent stdout messages doesn't appear on the screen, even though they occurred prior to the termination.

That's because stdout messages are first being written to buffer that is also erased upon termination without being written to stdout in advance.

My question is whether there's a generic option to flush all debug messages in c/c++ code before program terminate unexpectedly ? (I would prefer using some generic compiler configuration rather that an ad-hoc solution for a specific implementation such as std::cout - if there's such option, I'd be happy to know if it's common to GCC and G++)

Note : I assume that when flushing this buffer for each new arriving message, will damage performance. however, it's only meant for debug version.

thanks


Solution

  • Try setvbuf to set no buffer

    setvbuf(stream, NULL, _IONBF, 0)