How to pass macro definition from "make" command line arguments (-D) to C source code?
Call make
command this way:
make CFLAGS=-Dvar=42
And be sure to use $(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make
command will override the CFLAGS
value already defined the Makefile.
Alternatively you could set -Dvar=42
in another variable than CFLAGS
and then reuse this variable in CFLAGS
to avoid completely overriding CFLAGS
.
Just use a specific variable for that.
$ cat Makefile
all:
echo foo | gcc $(USER_DEFINES) -E -xc -
$ make USER_DEFINES="-Dfoo=one"
echo foo | gcc -Dfoo=one -E -xc -
...
one
$ make USER_DEFINES="-Dfoo=bar"
echo foo | gcc -Dfoo=bar -E -xc -
...
bar
$ make
echo foo | gcc -E -xc -
...
foo
Call make this way
make CFLAGS=-Dvar=42
because you do want to override your Makefile's CFLAGS, and not just the environment (which has a lower priority with regard to Makefile variables).