Is it possible to put the equivalent of #define VAR
(in a C program) into a makefile, so that one can control which part of the program should be compiled?

- 730,956
- 141
- 904
- 1,278

- 14,642
- 18
- 56
- 77
3 Answers
Accordingly to cc
manpage on linux
-D name=definition
The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In
particular, the definition will be truncated by embedded newline characters.

- 8,150
- 3
- 29
- 36
-
2Note that this is not Linux-specific. POSIX specifies `-D` for the `c99` command which is the standard name for the C compiler: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/c99.html – R.. GitHub STOP HELPING ICE Mar 15 '11 at 03:48
Edit your Makefile
to show
CFLAGS=-D VAR1 -D VAR2=*something*
If you are using default rules in the Makefile, this should work automatically. If you do not, and are invoking the C compiler explicitely, just make sure you are writing something along the lines of
$(CC) $(CFLAGS) -c -o $@ $<
Even more cute if the fact the CFLAGS=...
above can be used on the command line rather than written in the Makefile (read man(1)
manual page); this allows for easy reconfiguration of your compilation parameters at last moment, but the parameters won't be kept.
Best practices include using CPPFLAGS
instead of CFLAGS
, and using +=
instead of =
; however support for these features are not as universal as the above, and depend on your make system.

- 888
- 4
- 25
Yes.
Most compilers support command line options for specifying #define's. For Visual C++, this is the /D option.

- 54,279
- 5
- 125
- 144
-
2In fact, `-D` was used by some of the earliest C compilers, and remains nearly universally accepted. The only others I can think of that are nearly as close to universal are `-c` and maybe `-O`. – Jerry Coffin Mar 14 '11 at 18:00
-
Most of Microsoft's command line tools (`cl` included) accept `/` as well as `-` as argument prefix. Which means you can use `-D` and be compatible to `cl` as well as `gcc`. – Max Truxa Sep 15 '14 at 17:56