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:

make test TESTFLAGS=1

and then to check in the Makefile for its existence:

# Generic flags shared by all builds

# Check for test flag
ifeq ($(TESTFLAGS),)
   #empty flags, release setting
   CXXFLAGS += -O2
   #debug setting
   CXXFLAGS += -g3 -ggdb -O0 -fprofile-arcs -ftest-coverage

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:

#unittest target
$(TEST_TARGET): CXXFLAGS += -g3 -ggdb -O0 -fprofile-arcs -ftest-coverage
$(TEST_TARGET): $(OBJS) unittest.o $(TEST_OBJS)

#production build
$(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 :)