Append to GNU make variables via command line

Michael Koval picture Michael Koval · Jan 25, 2010 · Viewed 49.4k times · Source

I am using a GNU-make Makefile to build a C project with several targets (all, clean, and a few project specific targets). In the process of debugging, I would like to append some flags to a single build without permanently editing the Makefile (e.g. add debugging symbols or set a preprocessor flag).

In the past, I have done that as follows (using the debugging symbols example):

make target CFLAGS+=-g

Unfortunately, this is not appending to the CFLAGS variable, but instead, clearing it and stopping it from compiling. Is there a clean way of doing this without defining some sort of dummy variable appended to the end of CFLAGS and LDFLAGS?

Answer

Carl Norum picture Carl Norum · Jan 25, 2010

Check out the override directive. You will probably need to modify the makefile once, but it should do what you want.

Example makefile:

override CFLAGS += -Wall

app: main.c
    gcc $(CFLAGS) -o app main.c 

Example command lines:

$ make
gcc -Wall -o app main.c 
$ make CFLAGS=-g
gcc -g -Wall -o app main.c