Raunaq Kochar Raunaq Kochar - 1 month ago 8
Linux Question

'make' equivalent of -D flag as in gcc

My C code has various files having statements that I want to execute only if a macro is defined. I have two files each having the following code:

#ifdef SOME_MACRO
printf("macro defined\n");
#else
printf("macro undefined");
#endif


My Makefile contains:

make -C /lib/modules/$(shell uname -r )/build M=$(PWD) modules $(CFLAGS)


and I am calling make as:

make all CFLAGS=SOME_MACRO=10


When I execute the resulting program, I get 'macro undefined' indicating the macro is not being defined.

I have also tried calling it as:

make all CFLAGS=SOME_MACRO


which gives me:

make[1]: *** No rule to make target `SOME_MACRO'. Stop.
make[1]: Leaving directory `/X/Y/Z'
make: *** [default] Error 2


And also calling it as:

make all CFLAGS=-DSOME_MACRO=10


as given here and here but this is not working either.

How do I make this work?

Answer

The third form is correct (make all CFLAGS=-DSOME_MACRO=10 or just make all CFLAGS=-DSOME_MACRO). But the make file that you are calling has to actually use that CFLAGS macro.

Make's implicit rules for compiling an executable or object c file will use CFLAGS, but we can't tell whether it is being invoked or overridden without seeing either the content of that makefile or the output from make.

The output from make should show the build commands. The implicit rule for making a .o from a .c file is $(CC) $(CPPFLAGS) $(CFLAGS) -c so you should see something like cc -DSOME_MACRO=2 -DFOO=99 -c -o x.o x.c given you compiling an object file, and similar if you compiling a executable.

Also make sure your cleaning you project properly make clean. And make sure the clean is actually recursive (i.e. cleans you "modules" project too)...

Edit: Oh yeah ... as @nneonneo's answer points out you also have an error in recursive the make call which is definitely an issue (I figured you were running the 2nd make command directly to debug the problem..). The above may still apply.