Reputation: 2930
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.
Now I need 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 in main.c can see var
:
int main()
{
int i = var;
}
Upvotes: 143
Views: 185442
Reputation: 387
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).
CPPFLAGS
n.o
is made automatically from n.c
with a recipe of the form:
$(CC) $(CPPFLAGS) $(CFLAGS) -c
n.o
is made automatically from n.cc
, n.cpp
, or n.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.
Upvotes: 19
Reputation: 10579
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).
Upvotes: 10
Reputation: 145899
Call the 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 in 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
.
Upvotes: 139
Reputation: 1323
Find the C file and Makefile implementation in below to meet your requirements
foo.c
main ()
{
int a = MAKE_DEFINE;
printf ("MAKE_DEFINE value:%d\n", a);
}
Makefile
all:
gcc -DMAKE_DEFINE=11 foo.c
Upvotes: -3
Reputation: 108986
$ cat x.mak all: echo $(OPTION) $ make -f x.mak 'OPTION=-DPASSTOC=42' echo -DPASSTOC=42 -DPASSTOC=42
Upvotes: 2
Reputation: 206879
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
Upvotes: 15