【问题标题】:Runtime error using boost - undefined symbol: _ZN5boost6system15system_categoryEv使用 boost 的运行时错误 - 未定义的符号:_ZN5boost6system15system_categoryEv
【发布时间】:2017-10-26 13:39:06
【问题描述】:

我正在使用 CMake 编译一个简单的项目(共享库),这是 CMakeLists.txt 的内容

set (CMAKE_BUILD_TYPE Release)

set (LibName test)

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(test CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${warnings}")
add_definitions(${GCC_NARROWING})
add_definitions(${GCC_RESOLVEALL})
add_definitions(-DTESTFRAMEWORK_GOOGLE)
add_definitions(-DVARIADIC_MAX=10)
add_definitions(-DENCODING=8)

#include_directories(${GTEST_PATH}/include)
include_directories(${BOOST_PATH})    #${BOOST_PATH} is defined by parent CMakeList
include_directories(${GTEST_PATH}/include ../../ThirdParty/rapidjson_master/include)
set (SOURCES 
    ${CMAKE_CURRENT_SOURCE_DIR}/Test.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/Test.h
    )

message(${LibName})
add_library(${LibName} SHARED ${SOURCES})

target_link_libraries(${LibName} 
  ${OUTDIR}/libboost_system.a 
  ${OUTDIR}/libboost_thread.a
  ${OUTDIR}/libboost_chrono.a
  )

编译时我没有收到任何错误,当运行加载此共享库的程序时我收到:

./test.so: 未定义符号:_ZN5boost6system15system_categoryEv

加载此共享库的程序只需执行以下操作:

void *m_hTest = dlopen("./test.so", RTLD_NOW);
if (m_hTest == NULL) {
return -1;
}

共享库使用 Boost 的 Thread Local Storage,在一个类中,其中一个成员是:

boost::thread_specific_ptr<TLSData> threadData;

这是我在 boost 中唯一使用的东西

【问题讨论】:

  • 您使用的是什么平台/环境?通常,我使用find_package(Boost COMPONENTS system) 来查找提升。如果您使用包管理器安装了 boost,这通常可以正常工作。然后我使用target_link_libraries(${LibName} boost::system) 链接并导入适当的包含目录。有一些很棒的文档here
  • P.S.您描述的错误不是“运行时错误”。这是一个链接器错误。运行应用程序时会发生运行时错误。

标签: c++ boost cmake shared-libraries boost-system


【解决方案1】:

无论我使用 CMake 链接到 boost,我都使用 FindBoost.cmake

在你的情况下是这样的:

find_package(Boost COMPONENTS thread) 
target_link_libraries(${LibName} Boost::thread)

请注意,链接到Boost::&lt;target&gt; 与链接到libboost_&lt;target&gt;.a 并不完全相同,因为Boost::&lt;target&gt; 还引入了该目标的所有依赖项,包括其包含目录和依赖库。在这种情况下,显式链接到 Boost::systemBoost::chrono 实际上是不必要的,因为自从 Boost 版本 1.50.0 以来,boost::thread 实际上会隐式导入 system 和 chrono。

您不需要添加include_directories(${BOOST_PATH}),因为它由find_package 宏处理并与target_link_libraries 宏隐式链接。

如果您在查找 boost 时遇到问题,可以将 BOOST_ROOT 环境变量设置为安装 boost 的位置。如果您仍然无法解决 cmake 在哪里搜索库以及它试图链接的内容,您可以暂时set(Boost_DEBUG ON)

有时我在链接boost::logboost::chrono 时遇到问题,我发现添加以下内容通常会有所帮助:

target_link_libraries(${LibName}
                        Boost::disable_autolinking
                        Boost::dynamic_linking
                     )

这些目标将编译定义-DBOOST_ALL_NO_LIB-DBOOST_ALL_DYN_LINK 添加到您的项目中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多