Search code examples
unit-testingcmakegoogletest

cmake: how to separately compile production code and test code


I read this brilliant tutorial about how to integrate Google Test with CMake. The outline of the project there looks like this:

+-- CMakeLists.txt
+-- main
|    +-- CMakeLists
|    +-- main.cpp
|
+-- test
|    +-- CMakeLists.txt
|    +-- testfoo
|       +-- CMakeLists.txt
|       +-- main.cpp
|       +-- testfoo.h
|       +-- testfoo.cpp
|       +-- mockbar.h
|
+-- libfoo
|    +-- CMakeLists.txt
|    +-- foo.h
|    +-- foo.cpp
|
+-- libbar
     +-- CMakeLists.txt
     +-- bar.h
     +-- bar.cpp

(For the interested, the entire code of this example project can be checked out from here)

The top-level CMakeLists.txt contains (among others) the statements enable_testing() and add_subdirectory(test). Compiling and running test cases works perfectly with this setup, simply by running

mkdir build && cd build
cmake ..
make
make test

But how would I compile this project into production code, i.e. only the components test, libfoo and libbar, without all the unit tests?

Should I make the statements enable_testing() and add_subdirectory(test) somehow dependent on some build configuration variables? Or what's the best practice for this?


Solution

  • To build the tests only on request, I do it in this way:

    1. Add an option option(BUILD_TEST "Build the unit tests" ON)
    2. Include the test subdirs only in case BUILD_TEST is on

    if(BUILD_TEST) add_subdirectory(test) endif()

    In your case you can modify this to testfoo.

    As you asked for production, you can use the following instead to build in debug mode only:

    if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") add_subdirectory(test) endif()