I usually pass macro definitions from "make command line" to a "makefile" using the option : -Dname=value. The definition is accessible inside the makefile.
I also pass macro definitions from the "makefile" to the "source code" using the similar compiler option : -Dname=value (supported in many compilers). This definition is accessible in the source code.
What I need now, is to allow the user of my makefile to be able to pass arbitrary macro definitions from the "make.exe commandline" to "source code" right away, without having to change anything in the makefile.
so the user can type : make -f mymakefile.mk -SOMEOPTION var=5
then directly the code main.c can see var :
int main()
{
int i = var;
}
Just use a specific variable for that.
Find the C file and Makefile implementation in below to meet your requirements
foo.c
Makefile
Call
make
command this way:And be sure to use
$(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after themake
command will override theCFLAGS
value already defined the Makefile.Alternatively you could set
-Dvar=42
in another variable thanCFLAGS
and then reuse this variable inCFLAGS
to avoid completely overridingCFLAGS
.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 thanCFLAGS
orCXXFLAGS
, since it is described by the GNU Make manual as: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.More info
Call make this way
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).