I'm currently looking for a way to print messages from std::cerr to the terminal in red in order to draw attention to the user that an error has occurred while using my command line tool.
I'd like this to mostly be supported on OS X and Linux, but hopefully Windows later on. I'm already using Boost in my code if anyone is aware of something in the library I could use.
With Linux (not so sure about OS X, but as they're related I would expect so?) you can use ANSI escape codes to control text color (along with assorted other things). If the terminal supports is there. http://en.wikipedia.org/wiki/ANSI_escape_code
There are a number of threads on this subject scattered about the cplusplus.com forums:
However, I noticed that this changes the color for all terminal streams, and does so permanently, even after my program has terminated. After all this, I'm assuming there is no way to set only std::cerr to red for only my program while it is running. Are there any other alternatives, or am I forced to write my own personal program function to handle std::cerr messages?
error C2598: linkage specification must be at global scope
when I try to compile your function using MSVC as you're including <windows.h> inside a function; it needs to be included at global scope.
B) There's no GetConsoleTextAttribute(); you have to use GetConsoleScreenBufferInfo() to retrieve the current colour.
C) SetConsoleTextAttribute() doesn't just set the foreground color. For a general solution you really need to handle the background color (and other info) in the character attributes.
Here is what I have now. Again, no Windows computer at my access, which makes this very interesting to say the least. I've saved the user's standard settings into the error_buffer_info object. I'm just having difficulty researching how to set the text attributes to exactly the same except for a red foreground color.
Note I'm switching color to yellow if the background is red or magenta, using bright colors, and also a slightly different spelling of 'GenConsoleScreenBufferInfo'!