Search code examples
c++boostcmakeboost-test

How to properly configure boost test with cmake


Boost.Test is a very nice unit-testing library, but allways when I try to configure it in a new project it is a major pain.

How to configure my project, that uses cmake, to use boost with following requirements (this is really a list of things I disliked in most of the recipies I found on the internet):

  • I don't want to use single header variant of UTF (that is I don't want to include boost/test/included/unit_test.hpp). Rationale for this is that it slows down both compilation and IDE.
  • I don't really want to write a main function -- unless it is a one liner (I didn't find any copy-paste ways to define a main function). So unless you can provide such main snippet this means that Boost.Test is linked statically.
  • I don't want to include everyting statically (via -static gcc switch). I also dont really want to compile every boost component statically.
  • I don't want to hardcode any library paths in my cmake config.

So here is test.cpp I want to use:

#define BOOST_TEST_MODULE ExampleTest
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(ExampleSuite)

BOOST_AUTO_TEST_CASE( my_test )
{
    BOOST_CHECK(true);
}

BOOST_AUTO_TEST_SUITE_END()

And here is simple (not working!) CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.11)
project(example)
add_executable(simple-test tests.cpp)

Solution

  • Actually I didn't found any concrete solution that fulfills my need, but here are two partial solutions that are mostly OK.

    Explicitly link statically to libboost_unit_test_framework.a:

    In this case CMakeLists.txt looks like that:

    cmake_minimum_required(VERSION 2.8.11)
    project(example)
    ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
    SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES
        IMPORTED_LOCATION /usr/lib/x86_64-linux-gnu/libboost_unit_test_framework.a)
    add_executable(simple-test tests.cpp)
    target_link_libraries(simple-test boost_unit_test_framework)
    

    Drawbacks are that I explicitly link to a /usr/lib/x86_64-linux-gnu/libboost_unit_test_framework.a which can change (I guess).

    Use find_packages

    cmake_minimum_required(VERSION 2.8.11)
    set(Boost_USE_STATIC_LIBS ON)
    find_package(Boost COMPONENTS unit_test_framework REQUIRED)
    add_executable(simple-test tests.cpp)
    target_link_libraries(simple-test ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})
    

    Drawbaks for this is that (as far as I understand set(Boost_USE_STATIC_LIBS ON) forces all boost components to be linked statically, which might be undesirable.