3

我无法在我的 Mac 上构建一个使用 Boost.Test 的小程序,并在 MacPorts 上安装了 Boost/opt/local/lib/

这是我的最小源文件,test.cpp

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

BOOST_AUTO_TEST_CASE(test1) {
}

我的CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
project (test)
find_package(Boost COMPONENTS unit_test_framework REQUIRED)
add_executable(test test.cpp)

摘录自make VERBOSE=1

[100%] Building CXX object CMakeFiles/test.dir/test.cpp.o
g++ -o CMakeFiles/test.dir/test.cpp.o -c /Users/exclipy/Code/cpp/inline_variant/question/test.cpp
Linking CXX executable test
"/Applications/CMake 2.8-5.app/Contents/bin/cmake" -E cmake_link_script CMakeFiles/test.dir/link.txt --verbose=1
g++ -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/test.dir/test.cpp.o-o test
Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
  "vtable for boost::unit_test::unit_test_log_t", referenced from:
      boost::unit_test::unit_test_log_t::unit_test_log_t() in test.cpp.o
      boost::unit_test::unit_test_log_t::~unit_test_log_t() in test.cpp.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.

如您所见,它不知道如何链接到 Boost 库。所以我尝试添加到 CMakeLists.txt:

target_link_libraries(test boost_unit_test_framework)

但我只是得到:

g++ -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/test.dir/test.cpp.o-o test -lboost_unit_test_framework 
ld: library not found for -lboost_unit_test_framework

通过大量的试验和错误,我发现手动运行它是有效的:

$ g++ test.cpp -L/opt/local/lib -lboost_unit_test_framework -DBOOST_TEST_DYN_LINK

但是经过几个小时的摆弄,我无法从 CMake 构建它。我不在乎它是动态链接还是静态链接,我只想让它工作。

4

3 回答 3

5

您需要告诉 CMake 在哪里可以找到 boost 库(-L/opt/local/lib在您的 g++ 行中)。您可以通过添加以下行来完成此操作(如果您对 没有问题find_package):

link_directories ( ${Boost_LIBRARY_DIRS} )

之前add_executable

另一种选择是使用UTF 的单头变体。这个变体非常简单(您只需要包含<boost/test/included/unit_test.hpp>,但它的主要缺点是构建时间显着增加。

于 2012-03-17T08:15:04.260 回答
3

该调用收集CMake 变量中find_package(Boost COMPONENTS ...)搜索到的 Boost 组件(例如 )所需的链接库。unit_test_frameworkBoost_LIBRARIES

要摆脱链接错误,请添加:

target_link_libraries(test ${Boost_LIBRARIES})
于 2012-03-17T08:51:36.667 回答
1

编辑 2020-02

构建 Boost.Test 模块的详细信息在此处的文档中,并包含文档中的许多示例。通常如果main没有找到,这可能是由于:

  • 混合 Boost.Test 的静态和共享库版本(链接器更喜欢共享库)
  • BOOST_TEST_MODULE和/或宏的不正确定义BOOST_TEST_DYN_LINK:根据这些,Boost.Test 框架将(正确地)定义 amain或不定义。

上一个(错误的)答案

好吧,问题不在于 cmake 找不到boost_unit_test_framework库,而是这个特定的库不包含main运行二进制文件的入口点。

实际上,您应该链接反对,${Boost_TEST_EXEC_MONITOR_LIBRARY}因为它包含正确的定义。您还应该避免定义宏BOOST_TEST_DYN_LINK

于 2013-04-25T07:38:03.760 回答