reversed(top()) code tags rss about

Enabling output colorization in GCC

October 25, 2015
[gcc] [color] [terminal] [programming] [ccache] [issue]

I was waiting for GCC 4.9 for a while to get my hands on colorized color output, but after it became available in Slackware error output didn’t magically become colored. This might not be the case for other distributions, but since it took me some time to make this work and after more than six month I still can’t find any related posts on the Internet right away here’s a short note.

How to enable it?

There is a new option:

-fdiagnostics-color=[auto|never|always]

The manual page says:

The default is never if GCC_COLORS environment variable isn't present in the
environment, and auto otherwise.

We want auto (to do not put escape sequences on redirecting output), so naturally one would just define $GCC_COLORS in .bashrc (or equivalent):

export GCC_COLORS=

The catch is that nothing will change, the value must specify coloring, the simplest way would be to use defaults provided in the manual:

export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

Try it out, does it work? If not, then…

Are you using ccache?

If output of gcc/g++ is not colored, what about /usr/bin/gcc//usr/bin/g++? If that works and gcc is a symbolic link to ccache executable, it’s the one to blame.

As ccache redirects output of a compiler to something that is not a terminal and we just defined $GCC_COLORS to use auto-mode, which is “colorize only if output is a terminal” (see man 3 isatty if you don’t know how to implement this), nothing will be colored.

By the time I had this issue, corresponding patch was applied to the ccache for some time and I had to just upgrade it (at that time by building it myself). So keep this in mind if you don’t see colored output without explicit -fdiagnostics-color=always option. The simplest way to remind yourself whether you’re using ccache is to run:

$ ls -l `which gcc`

Conclusion

Now, everything should work as expected.

Enabling coloring in GCC is somewhat not obvious at first, but makes sense in terms of compatibility and after all not all people might want to colorize the output and would prefer to keep it as it used to be.

By the way, while reading up on this subject I trapped on a page by some clang-lover, who claimed that GCC has stolen colorization feature from clang. Well, this seems to be terrible misunderstanding because clang implemented colorization being inspired by colorgcc script. GCC even had corresponding ticket for years, but developers weren’t inclined to add this into compiler itself because standalone script did just fine.