C++使用带有Cmake的Boost日志记录无法编译



我正在尝试使用CMake的boost日志库编译C++。

下面是一个简单的例子我的CPP文件-logtests.CPP

#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/expressions.hpp>
namespace logging = boost::log;
void init_logging()
{
logging::add_file_log("sample.log");
logging::core::get()->set_filter
(
logging::trivial::severity >= logging::trivial::info
);
}
int main(int, char*[])
{
init_logging();
BOOST_LOG_TRIVIAL(trace) << "This is a trace severity message";
BOOST_LOG_TRIVIAL(debug) << "This is a debug severity message";
BOOST_LOG_TRIVIAL(info) << "This is an informational severity message"; 
BOOST_LOG_TRIVIAL(warning) << "This is a warning severity message";
BOOST_LOG_TRIVIAL(error) << "This is an error severity message";
BOOST_LOG_TRIVIAL(fatal) << "and this is a fatal severity message";
std::cin.get();
return 0;

如果我将g++与以下参数一起使用,它编译并运行时不会出现问题。

#g++ includes/screwAround/logtest.cpp -DBOOST_LOG_DYN_LINK -o logtest -lboost_log -lboost_system -lboost_thread -pthread

但是如果我使用这个CMakeLists.txt,它会失败。

cmake_minimum_required(VERSION 3.6.3)
project(logtest)
# Enable C+11
#set(CMAKE_CXX_STANDARD 11)
ADD_DEFINITIONS(-DBUILD_SHARED_LIBS=ON)
# Library source files
ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK)
FIND_PACKAGE(Boost 1.67 COMPONENTS log thread system log_setup filesystem REQUIRED)
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)

INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
# Create example executable
add_executable(logtestcase logtest.cpp)
TARGET_LINK_LIBRARIES(logtestcase ${Boost_LOG_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} )

出现此错误:

/usr/bin/ld: CMakeFiles/logtestcase.dir/logtest.cpp.o: undefined reference to symbol '_ZN5boost6detail12get_tss_dataEPKv'
/usr/bin/ld: //lib/arm-linux-gnueabihf/libboost_thread.so.1.67.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/logtestcase.dir/build.make:85: logtestcase] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/logtestcase.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

根本原因似乎是CMake不包括Threads包,我曾尝试将Threads::Threads添加到target_link_libraries中,如图所示,但没有成功。

如果您想使用动态多线程Boost库,您需要在查找Boost:之前设置Boost_USE_STATIC_LIBSBoost_USE_MULTITHREAD标志

set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREAD ON)
FIND_PACKAGE(Boost log log_setup)

这些标志已记录在案。


我还建议您在链接时使用Boost::<component>导入的目标:

TARGET_LINK_LIBRARIES(logtestcase Boost::log)

最新更新