【问题标题】:cmake set linker flags for boostcmake 为 boost 设置链接器标志
【发布时间】:2012-12-17 17:36:50
【问题描述】:

我正在尝试从 http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/tutorial/tuttimer1.html 编译一个 boost 教程示例。

我的 CMakeLists.txt 如下所示:

project(boost)
add_executable(timer1 timer1.cpp)
set_target_properties(timer1 PROPERTIES LINK_FLAGS -lboost_system,-lpthread)

尝试用 cmake 构建整个东西,我得到:

/var/www/C++/boost/build$ make
-- Configuring done
-- Generating done
-- Build files have been written to: /var/www/C++/boost/build
Scanning dependencies of target timer1
[100%] Building CXX object CMakeFiles/timer1.dir/timer1.cpp.o                                                                                                    
Linking CXX executable timer1                                                                                                                                    
/usr/bin/ld: cannot find -lboost_system,-lpthread                                                                                                                
collect2: ld returned 1 exit status
make[2]: *** [timer1] Błąd 1
make[1]: *** [CMakeFiles/timer1.dir/all] Błąd 2
make: *** [all] Błąd 2

但是当我跑步时:

g++ timer1.cpp -lboost_system -lpthread -o timer1

手动,一切正常。有人可以指出我做错了什么吗?

PS 当我尝试使用Turning on linker flags with CMake 中描述的解决方案时,我在 cmake 中添加了以下几行:

set(CMAKE_SHARED_LINKER_FLAGS "-lboost_system,-lpthread")
set(CMAKE_MODULE_LINKER_FLAGS "-lboost_system,-lpthread")
set(CMAKE_EXE_LINKER_FLAGS "-lboost_system,-lpthread")

我得到与上面相同的错误。

【问题讨论】:

    标签: linker cmake


    【解决方案1】:

    我强烈建议您使用 CMake 集成的 FindPackage。 CMake 会为你找到 boost 和 pthreads。

    您的 CMakeLists.txt 应如下所示:

    find_package( Boost COMPONENTS thread system filesystem REQUIRED ) #whatever libs you need
    include_directories( ${Boost_INCLUDE_DIRS} )
    find_package( Threads )
    

    在子文件夹 src 中:

    set( LIBS_TO_LINK
        ${Boost_LIBRARIES}
        ${CMAKE_THREAD_LIBS_INIT}
    )
    
    target_link_libraries( myApp
        ${LIBS_TO_LINK}
    )
    

    【讨论】:

      【解决方案2】:

      /usr/bin/ld: 找不到-lboost_system,-lpthread

      链接器在这里寻找库libboost_system,-lpthread.so。在任何 UNIX 系统上不可能存在这样的库。

      你可能想要:

      set(CMAKE_EXE_LINKER_FLAGS "-lboost_system -lpthread")
      

      【讨论】:

      • 现在我得到:链接 CXX 可执行服务器 CMakeFiles/server.dir/server.cpp.o:在函数 __static_initialization_and_destruction_0(int, int)': server.cpp:(.text+0x810): undefined reference to boost::system::generic_category()' [...] collect2: ld 返回 1 退出状态 make[2]: *** [server] 错误 1 ​​make[1]: *** [CMakeFiles/server.dir/all] 错误 2 make: *** [all] 错误 2
      • @tkoomzaaskz 此错误通常意味着您将C++ 可执行文件与普通-C (gcc) 编译器链接。我不知道如何告诉 CMake 它应该使用 g++ 而不是 gcc。一种可能的解决方法是将-lstdc++ 添加到LINKER_FLAGS 列表中,但我建议仅在您无法找出正确的g++ 解决方案时使用它。
      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2012-09-06
      • 2017-12-23
      • 2019-01-01
      • 2021-04-01
      相关资源
      最近更新 更多