How do I pass the macro definition from the "make" (-D) command line arguments to the C source code?

I usually pass macro definitions from the "make command line" to the "makefile" with the option: -Dname = value. The definition is available inside the makefile.

I also pass macros from the "makefile" to the "source code" using a similar compiler option: -Dname = value (supported by many compilers). This definition is available in source code.

Now I need the user of my make file to be able to transfer arbitrary macros from the "make.exe commandline" to the "source code" right away without changing anything in the make file.

so that the user can enter: make -f mymakefile.mk -SOMEOPTION var = 5

then directly the main.c code can see var:

int main() { int i = var; } 
+61
c macros makefile
Jan 29 '12 at 11:22
source share
5 answers

Call make as follows:

 make CFLAGS=-Dvar=42 

And don't forget to use $(CFLAGS) in your compilation command in the Makefile. As @ jørgensen noted, assigning a variable after the make overrides the CFLAGS value already defined by the Makefile.

Alternatively, you can set -Dvar=42 to a different variable than CFLAGS and then reuse this variable in CFLAGS to avoid overriding CFLAGS completely.

+62
Jan 29 '12 at 11:48
source share

Just use a specific variable for this.

 $ 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 
+7
Jan 29 '12 at 11:48
source share

Call this way

 make CFLAGS=-Dvar=42 

because you want to override CFLAGS Makefile, not just the environment (which has a lower priority with respect to Makefile variables).

+7
Jan 29 '12 at 12:01
source share
 $ cat x.mak
 all:
     echo $ (OPTION)
 $ make -f x.mak 'OPTION = -DPASSTOC = 42'
 echo -DPASSTOC = 42
 -DPASSTOC = 42
+1
Jan 29 2018-12-12T00:
source share

Find the implementation of the C file and Makefile below according to your requirements

foo.c

  main () { int a = MAKE_DEFINE; printf ("MAKE_DEFINE value:%d\n", a); } 

Makefile

 all: gcc -DMAKE_DEFINE=11 foo.c 
-3
Aug 11 '14 at 4:49
source share



All Articles