A Makefile for TDD with C++

Post by Nico Brailovsky @ 2011-08-22 | Permalink | 1 comments | Leave a comment

So, after reading my post about makefiles you decided that you like them but would like to add some TDD to be buzzword compliant? No problem, that's easy to do.

Assuming you use a naming convention such as this one:

path/to/src/Object.h
path/to/src/Object.cpp
path/to/src/Object_Test.cpp

then it's easy to auto detect which tests should be built:

TEST_SRCS := $(patsubst ./%, %, $(shell find -L|grep -v svn|egrep "_Test.cpp$$" ) )
TEST_BINS := $(addprefix ./$(BIN_DIR)/, $(patsubst %.cpp, %, $(TEST_SRCS)) )

Then we have to define a special rule with pattern matching to compile the tests:

$(BIN_DIR)/%_Test: $(patsubst $(BIN_DIR)/%, %, %_Test.cpp ) %.cpp %.h
    @echo "Making $@"
    @mkdir -p $(shell dirname $@)
    g++ $(CXXFLAGS) -g3 -O0 $< -o $@ -lpthread -lgtest_main -lgmock $(OBJECTS) $(LDFLAGS)

and some magic to auto execute every test when we "make test":

test: $(TEST_SRCS)
    @for TEST in $(TEST_BINS); do
        make "$$TEST";
        echo "Execute $(TEST)";
        ./$$TEST;
    done

Everything nice and tidy for a copy & paste session:

TEST_SRCS := $(patsubst ./%, %, $(shell find -L|grep -v svn|egrep "_Test.cpp$$" ) )
TEST_BINS := $(addprefix ./$(BIN_DIR)/, $(patsubst %.cpp, %, $(TEST_SRCS)) )
$(BIN_DIR)/%_Test: $(patsubst $(BIN_DIR)/%, %, %_Test.cpp ) %.cpp %.h
    @echo "Making $@"
    @mkdir -p $(shell dirname $@)
    g++ $(CXXFLAGS) -g3 -O0 $< -o $@ -lpthread -lgtest_main -lgmock $(OBJECTS) $(LDFLAGS)
.PHONY: test
test: $(TEST_SRCS)
    @for TEST in $(TEST_BINS); do
        make "$$TEST";
        echo "Execute $(TEST)";
        ./$$TEST;
    done

Now you just need to run make test. Remember to add the proper Vim's mapping.


In reply to this post, Nicolás Brailovsky » Blog Archive » A Makefile for code coverage report with C++ commented @ 2011-08-30T11:14:37.000+02:00:

[...] far you should know how to use makefiles and you should have a nice testable project. Then you have everything ready to get a coverage [...]

Original published here.