Makefile functions and color output

December 18th, 2013 at 5:54 am

When writing non-trivial makefiles, two needs occur occasionally. One is some way to collect common commands together without duplicating too much code. Another is adding color to some output, making it stand out (for example, this is done by makefiles generated by CMake).

Here’s a short makefile snippet that shows how to achieve this on modern Linux terminals:

define colorecho
      @tput setaf 6
      @echo $1
      @tput sgr0
endef

Defines a makefile function named colorecho, with a single argument which is exposed via $1. This function sets the terminal color to cyan with tput, echoes its argument and resets the terminal settings to default.

Here’s how this function can be called:

$(call colorecho,"Linking with" $(LD))
$(LD) $^ -o $@

Related posts:

  1. Anonymous functions (lambdas) in C++11
  2. spam-filters on output
  3. Keeping persistent history in bash

6 Responses to “Makefile functions and color output”

  1. Maxim YegorushkinNo Gravatar Says:

    That macro ends up invoking the shell three times. You may like to make it a one-liner.

  2. DukalesNo Gravatar Says:

    It will be better if you tell us about how to make the gdb to output colored JIT-code-related-source-code =) (excuse me for a little chutzpah). I know this problem can be solved (literally) only by you. At the moment, unfortunatelly, I waste (without any result) 450 reputation for bounty on SO with objective to get an idea of ​​how the GDB JIT Interface simpliest example looks on C++ (http://stackoverflow.com/questions/20046943/). I sure, that this issue is definitely in the spectrum of the problems, that are usually at your issue.

  3. elibenNo Gravatar Says:

    @Dukales,

    You’re too dramatic! I’ll take a look at your SO question

  4. Stan AngeloffNo Gravatar Says:

    To colour output, shouldn’t /bin/echo -e be sufficient? Referencing the binary works around the built-in ‘echo’ function which sometimes doesn’t support escape sequences.

  5. TomasNo Gravatar Says:

    Hi Eli.
    The link to the bash HOWTO manual is not working
    It seems you might have pasted the url twice.
    Just in case you wanna fix it.
    Regards,
    Tomas.

  6. elibenNo Gravatar Says:

    @Tomas,

    Thanks, fixed.

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)