I'm trying to write a makefile which supports release mode and debug mode, while in debug mode, I want to link an extra object debug.o
to override functions for debugging.
For example:
CFLAGS = -Wall -I$(INCPATH)
INCPATH = include
TARGET = foo
OBJ = foo.o bar.o
# release mode
all: build run clear
# debug mode
debug: CFLAGS += -g -DDEBUG
debug: OBJ += debug.o
debug: build gdb-run clear
# link objects
build: $(OBJ)
gcc $(CFLAGS) -o $(TARGET) $(OBJ)
# compile source code
%.o: %.c $(INCPATH)/*.h
gcc $(CFLAGS) -c $@ $<
# default run mode
run:
./$(TARGET)
# debug run mode
gdb-run:
gdb --args $(TARGET)
clear:
rm -f $(OBJ) $(TARGET)
I expected it expand $(OBJ)
to foo.o bar.o debug.o
when I call make debug
, but instead it only expands to foo.o bar.o
, because targets are expanded immediately when parsed.
I've tried using .SECONDEXPANSION:
, but couldn't work it out.
And I've also tried $(eval OBJ += debug.o)
, but that resulted in expanding $(OBJ)
to foo.o bar.o debug.o
even while running make all
.
Is this possible, or should I just work around?
edit: fixed a typo, thanks to @matt