Reputation: 1941
I have created a (very simple) makefile:
DEBUG = -DDEBUG
main: main.c add.c
gcc $(DEBUG) main.c add.c -o main -lm
What I want (and don't understand how to do), is to create the makefile so that if the user prints make debug
, the code will compile with the debug option, but when printing only make
, the debug will be left out. What is the best way to do this?
Upvotes: 6
Views: 16969
Reputation: 320
This may be late, ...
The basic idea is to build all objects in the subdirectory, say ./build
.
We create a release file in ./build when we compile with make
and create a debug file when make debug
. So if there is a release file when make debug
, remove everything in ./build and then build.
all: $(BD)/release $(bin1) $(bin2)
debug: CFLAGS += -g -DDEBUG=1
debug: CXXFLAGS += -g -DDEBUG=1
debug: $(BD)/debug $(bin1) $(bin2)
$(BD)/%.o: %.c Makefile # changes in Makefile will cause a rebuild
@mkdir -p $(BD)
$(CC) $(CFLAGS) -c -o $@ $<
$(BD)/%.o: %.cpp Makefile
@mkdir -p $(BD)
$(CXX) $(CXXFLAGS) -c -o $@ $<
$(BD)/release:
@if [ -e $(BD)/debug ]; then rm -rf $(BD); fi
@mkdir -p $(BD)
@touch $(BD)/release
$(BD)/debug:
@if [ -e $(BD)/release ]; then rm -rf $(BD); fi
@mkdir -p $(BD)
@touch $(BD)/debug
Upvotes: 1
Reputation: 200
I came up with this solution, that depends on bash variable substitution.
Makefile:
main: main.c add.c
${CC} `echo $${DEBUG+-DDEBUG}` main.c add.c -o main -lm
When environment variable DEBUG is defined to anything (even blank), this makefile will substitute the -DDEBUG
useful to the compiler. So invocation looks like:
DEBUG=1 make main
Upvotes: 0
Reputation: 1977
You probably are looking for something like
main: main.c add.c
gcc $(DEBUG) main.c add.c -o main -lm
debug: DEBUG = -DDEBUG
debug: main
Upvotes: 10