I'm writing a program in c and I want to optionally compile a translationunit based on whether the user wants to or not. Basically I have two files, one main.c which should always be compiled. Moreover I have a file let's, call it optional.c. Some functions in optional.c are much faster than those in main.c but they are also more prone to errors.

In my main.c I can write code like

some function call from optional.c
some function call from main.c

In my makefile I also want to compile optional.c only if it should be used, say

gcc -c optional.c
gcc -c -DUSE_OPTIONAL main.c
gcc main.o optional.o

and if not, simply

gcc -c main.c
gcc main.o

It works to have two different rules, one called "all:" and one called "optional:" but I would prefer only typing "make" instead of "make optional". What is the simplest way to implement this? Should I turn to a configure script and a Makefile.in or is it better to just have a second rule? Is it possible to implement for example "make USE_OPTIONAL=1" and then have make read the input of the variable USE_OPTIONAL to figure out what to do?

1 Answer 1


You can use similar approaches to your C pre-processor directives in Makefiles, at least if you’re using GNU Make:



program: main.o optional.o


program: main.o


With this in place, any value given to USE_OPTIONAL in the make invocation will result in the optional features being included.

If you want a more specific test, you can use

ifeq ($(USE_OPTIONAL), 1)

instead of the ifdef line. Then you would need specifically make USE_OPTIONAL=1.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .