Matthieu Raynaud de Fitte Matthieu Raynaud de Fitte - 1 year ago 37
C Question

Makefile C/C++ with function depending of environment

I am struggling with the following problem :

I would like to use tput in my Makefile for color but it needs the environment variable $TERM ( and the echo alternative with \033[0;31m is not portable and will no behave the same way on all computers ).

When on an environment that does not have the variable, make fails and the program is not compiled.
I already tried searching for environment variable testing in a Makefile but with no success so far.

This is an example of what I would like to do :

define my_color
@tput setaf $2
@tput bold
@echo $1
@tput sgr0

CC = gcc

CFLAGS = -Wall -Wextra

SRCS = my_super_file.c

OBJS = $(SRCS:.c=.o)

NAME = super_programm

all: $(NAME)

$(NAME): $(OBJS)
$(call my_color, " Compiling $<", 2)
$(CC) -o $(NAME) $(OBJS)

rm -rf $(OBJS)

fclean: clean
rm -rf $(NAME)

re: fclean all

.PHONY: all re clean fclean

a more complete example here :

both will work just fine any computer but not on my server

What I am trying to do is have only one Makefile capable of working on both my computer and my server, I tried looking at the function ifeq but I did not succeed in getting it to work.

Any help will be greatly appreciated thank you for reading.

Answer Source

I think this makefile illustrates what you want:

have_term := $(shell echo $$TERM)

ifdef have_term
define my_color = 
    @tput setaf $2
    @tput bold
    @echo $1
    @tput sgr0
my_color = @echo $1

    $(call my_color, "Hello world", 2)

If TERM is defined in the environment then make prints Hello World in green, otherwise in plain white.

See 7.2 Syntax of Conditionals