syntax highlight

Monday 22 August 2011

A Makefile for TDD with C++

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.

1 comment:

  1. [...] 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 [...]

    ReplyDelete