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

MohamedEzz picture MohamedEzz · Jan 29, 2012 · Viewed 119.1k times · Source

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;
}

Answer

ouah picture ouah · Jan 29, 2012

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.