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.

Advertisements

One Comment on “A Makefile for TDD with C++”

  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 […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s