Thursday, October 08, 2009

Color Coding Makefile Output

Quick useful tidbit... color coding makefile output...

NO_COLOR=\x1b[0m

OK_COLOR=\x1b[32;01m

ERROR_COLOR=\x1b[31;01m

WARN_COLOR=\x1b[33;01m


OK_STRING=$(OK_COLOR)[OK]$(NO_COLOR)

ERROR_STRING=$(ERROR_COLOR)[ERRORS]$(NO_COLOR)

WARN_STRING=$(WARN_COLOR)[WARNINGS]$(NO_COLOR)

You can then echo out $(OK_STRING), $(ERROR_STRING) or $(WARN_STRING) depending on if errors were encountered. Errors are Red, Warnings are Yellow, Success is Green. If you want to know what the goofy strings like "\x1b[32;01m" actually mean, well it really should be obvious, duh! But in case you can't decode that enigma of a color coding scheme you can read about it here.

The only tricky bit then is just conditionally echoing the right string. Personaly I found the easiest way is to use temporary files to determine if the build was a success or had errors/warnings . But maybe there is a cleaner solution that doesn't require temp files?

@$(ECHO) -n compiling debug foo.cpp...


@$(CXX) $(CFLAGS) -c foo.cpp -o $@ 2> temp.log || touch temp.errors


@if test -e temp.errors; then $(ECHO) "$(ERROR_STRING)" && $(CAT) temp.log; elif test -s temp.log; then $(ECHO) "$(WARN_STRING)" && $(CAT) temp.log; else $(ECHO) "$(OK_STRING)"; fi;


@$(RM) -f temp.errors temp.log

For those that don't like writing makefiles explicitly, XPJ currently supports this color coding mechanism and leaves the OK/ERROR/WARN strings defined in the user specified platform file so you can alter the colors or disable them entirely.

3 comments:

Livenletdie said...

Super useful trick. Thanks.

jowi24 said...

The "|| touch temp.errors" prevents make from detecting the non-zero return code of CXX in case of an error. Thus make will not stop compilation any more.

James Dolan said...

So I actually recommend against using my method here if you plan running make with -j. Maybe someday I revisit it though to try and make it parallel make friendly.