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
.
Because of low reputation, I cannot comment the accepted answer.
I would like to mention the predefined variable CPPFLAGS
.It might represent a better fit than CFLAGS
or CXXFLAGS
, since it is described by the GNU Make manual as:
Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).
Examples of built-in implicit rules that use CPPFLAGS
n.o
is made automatically fromn.c
with a recipe of the form:$(CC) $(CPPFLAGS) $(CFLAGS) -c
n.o
is made automatically fromn.cc
,n.cpp
, orn.C
with a recipe of the form:$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c
One would use the command make CPPFLAGS=-Dvar=123
to define the desired macro.