Specific CXXFLAGS for each makefile target
The problem: my Makefile has two targets. One for a production buid and one for a unittest build. For the unittest build, I want to specify different CXXFLAGS (disable optimization for instance). This turns out to be difficult!
One option is to specify some variable on the make command line like this:
1
make test TESTFLAGS=1
and then to check in the Makefile for its existence:
1
2
3
4
5
6
7
8
9
10
11
# Generic flags shared by all builds
CXXFLAGS=-Wall
# Check for test flag
ifeq ($(TESTFLAGS),)
#empty flags, release setting
CXXFLAGS += -O2
else
#debug setting
CXXFLAGS += -g3 -ggdb -O0 -fprofile-arcs -ftest-coverage
endif
Of course, this is cumbersome! So I figured out you can specify requirements for each build target spanning multiple lines. This allows you to specify it like this:
1
2
3
4
5
6
7
#unittest target
$(TEST_TARGET): CXXFLAGS += -g3 -ggdb -O0 -fprofile-arcs -ftest-coverage
$(TEST_TARGET): $(OBJS) unittest.o $(TEST_OBJS)
#production build
$(TARGET): CXXFLAGS += -O2
$(TARGET): $(OBJS) main.o $(TEST_OBJS)
Of course the same trick will work for other variables like LDFLAGS. I've been searching and experimenting for this trick a long time, I thought sharing this would be nice :)
This post is licensed under CC BY 4.0 by the author.