我无法在我的 Mac 上构建一个使用 Boost.Test 的小程序,并在 /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 构建它。我不在乎它是动态链接还是静态链接,我只想让它工作。
最佳答案
您需要告诉 CMake 在哪里可以找到 boost 库(g++ 行中的 -L/opt/local/lib
)。您可以通过添加以下行来完成此操作(如果 find_package
没有问题):
link_directories ( ${Boost_LIBRARY_DIRS} )
在 add_executable
之前.
另一种选择是使用 the single-header variant of the UTF .这个变体非常简单(您只需要包含 <boost/test/included/unit_test.hpp>
,但它的主要缺点是构建时间显着增加。
关于使用 CMake 进行 Boost 测试 - 未定义的 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746065/