Arty
Arty

Reputation: 355

Add flags on Makefile compilation only if a parameter is given

I would like to know how the CFLAGS variable could be removed from the compilation and added when a parameter is given to the Makefile like "make cflags" without having to duplicate the compilation.

Here is a part of my Makefile :

EXE =   $(PATH_EXE)/COLLECTEUR

all:    ${EXE}

clean:
    rm -f ${PATH_OBJ}/*.o
    rm -f ${PATH_EXE}/*

clean_bin:
    rm -f ${PATH_EXE}/*

link:
    rm -f ${PATH_EXE}/*


$(PATH_EXE)/COLLECTEUR: $(PATH_OBJ)/Test.o $(OBJS) 
    ${LD}  ${CFLAGS} ${OBJS} $(PATH_OBJ)/Test.o  ${LDFLAGS}  -o $@


$(PATH_OBJ)/%.o  : %.c
    ${CC}  ${CFLAGS} $< -o $@

Upvotes: 1

Views: 908

Answers (1)

Anya Shenanigans
Anya Shenanigans

Reputation: 94584

The general trick in make is to use a feature known as a target specific variable, which allows you to set or append to variables if a specific target is given, like so:

cflags: CFLAGS+=-Wall -Werror

cflags: all

What this says is for the target cflags append -Wall -Werror to the cflags, and the following line says that the cflags target depends on the all target.

Now, I did notice some errors in your compilation options.

The final link line ${LD} will invoke ld, which doesn't take ${CFLAGS} by default, you're probably better off using the compiler driver there as well (replace the ${LD} with ${CC}).

The compilation line for $(PATH_OBJ)/%.o files compiles and links the files, because it's missing the -c option, which instructs the compiler to compile only, and not to link.

Upvotes: 3

Related Questions