Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating makefile with debug option

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?

like image 665
user16655 Avatar asked Oct 21 '14 09:10

user16655


2 Answers

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
like image 100
downhillFromHere Avatar answered Sep 28 '22 22:09

downhillFromHere


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
like image 21
ABacker Avatar answered Sep 28 '22 20:09

ABacker