简体   繁体   中英

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 $@

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM