Search code examples
cmacrosmakefile

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


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

Solution

  • 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.