【问题标题】:C++ Using Boost logging with Cmake fails to compileC++ 使用带有 Cmake 的 Boost 日志记录无法编译
【发布时间】:2022-01-20 19:04:54
【问题描述】:

我正在尝试使用带有 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 中,如 here 所示,但没有成功。

【问题讨论】:

标签: c++ cmake boost-log


【解决方案1】:

如果你想使用动态多线程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)

这些标志是documented


我还建议您在链接时使用 Boost::&lt;component&gt; 导入的目标:

TARGET_LINK_LIBRARIES(logtestcase Boost::log)

【讨论】:

  • 谢谢,多线程标志似乎没有帮助,但链接库 Boost::log 修复了它。
猜你喜欢
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2016-01-15
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
相关资源
最近更新 更多