Nicolás Brailovsky


A modern blog

A Makefile for TDD with C++

author Posted by: nico on date Aug 22nd, 2011 | filed Filed under: Makefiles, Programming

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:

  1. path/to/src/Object.h
  2. path/to/src/Object.cpp
  3. path/to/src/Object_Test.cpp

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

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

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

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

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

  1. test: $(TEST_SRCS)
  2.         @for TEST in $(TEST_BINS); do \
  3.                 make "$$TEST"; \
  4.                 echo "Execute $(TEST)"; \
  5.                 ./$$TEST; \
  6.         done

Everything nice and tidy for a copy & paste session:

  1. TEST_SRCS := $(patsubst ./%, %, $(shell find -L|grep -v svn|egrep "_Test\.cpp$$" ) )
  2. TEST_BINS := $(addprefix ./$(BIN_DIR)/, $(patsubst %.cpp, %, $(TEST_SRCS)) )
  3.  
  4. $(BIN_DIR)/%_Test: $(patsubst $(BIN_DIR)/%, %, %_Test.cpp ) %.cpp %.h
  5.         @echo "Making $@"
  6.         @mkdir -p $(shell dirname $@)
  7.         g++ $(CXXFLAGS) -g3 -O0 $< -o $@ -lpthread -lgtest_main -lgmock $(OBJECTS) $(LDFLAGS)
  8.  
  9. .PHONY: test
  10. test: $(TEST_SRCS)
  11.         @for TEST in $(TEST_BINS); do \
  12.                 make "$$TEST"; \
  13.                 echo "Execute $(TEST)"; \
  14.                 ./$$TEST; \
  15.         done

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

tagOne Response to “A Makefile for TDD with C++”

  1. Nicolás Brailovsky » Blog Archive » A Makefile for code coverage report with C++ Said,

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

     Add A Comment

trackback Trackback URI | rsscomment Comments RSS