Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Shared Library

To build Boost.Test as a shared library, first build the boost build tools, as described in the Getting Started documentation. After you have bootstrapped the build tools, build the test library with by invoking b2 with arguments similar to the following:

b2 --with-test link=shared

This will place the resulting libraries in stage/lib at the top level of the boost tree.

In a shared library configuration, Boost.Test is compiled into a single shared library named boost_unit_test_framework and the test executable is linked against that library to import symbols from the library. The Boost.Test shared library must be available to the runtime loader in order for the tests to execute. Every compilation unit that includes a header from Boost.Test must define BOOST_TEST_DYN_LINK first so that declarations are properly annotated as imported symbols. When BOOST_TEST_DYN_LINK is defined, Boost.Test also defines BOOST_TEST_ALTERNATIVE_INIT_API.

Exactly one compilation unit in the test executable should define BOOST_TEST_MAIN, in order run the tests.

// In exactly one compilation unit
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

// test cases (optional)

Additional source files define BOOST_TEST_DYN_LINK, include the main unit test header and define more test cases and/or suites.

// In additional source files
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

// test cases

To compile the library with no implementation of main, add BOOST_TEST_NO_MAIN to the cxxflags property for b2:

b2 --with-test link=shared define=BOOST_TEST_NO_MAIN

When the library is compiled with BOOST_TEST_NO_MAIN defined, one source file must provide a definition for main. The simplest is to delegate to unit_test_main and provide an implementation of an initialization function that manually adds test cases and suites to the test tree. Any test cases or test suites added with BOOST_AUTO_TEST_CASE, BOOST_FIXTURE_TEST_CASE, BOOST_AUTO_TEST_SUITE or BOOST_FIXTURE_TEST_SUITE are automatically added.

// In exactly one source file
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

bool init_function()
{
    // create test cases and suites and return a boolean indicating
    // success (true) or failure (false).
    return true;
}

int main(int argc, char* argv[])
{
    return ::boost::unit_test::unit_test_main(&init_function, argc, argv);
}

Example Source Code

PrevUpHomeNext