4

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?

1
  • You can make CMake command calls only dependent on the build configuration in single configuration make environments. I'm wondering if you know about EXCLUDE_FROM_DEFAULT_BUILD_<CONFIG> target property?
    – Florian
    Jan 19, 2017 at 9:07

2 Answers 2

4

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()

1

What I do is to make a custom macro for unit test creation which does this:

set_target_properties(${NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/test)

Then your tests will end up in a special directory (test) instead of the regular one (usually bin). Then for production you just copy the regular directory without the test directory.

1
  • So you say that you generally always build both production and test code? Ok, the more I think about it, the more I agree with it (though in this case building the test code might sometimes be a bit heavy, as it also downloads and builds googletest - but there are solutions to that). Actually the separation to different output directories is done already. I'm not quite sure what advantage the command you posted would bring.
    – Georg P.
    Jan 19, 2017 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.