cmake 为 boost 设置链接器标志

duc*_*cin 4 linker cmake

我正在尝试从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)
Run Code Online (Sandbox Code Playgroud)

试图用 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
Run Code Online (Sandbox Code Playgroud)

但是当我运行时:

g++ timer1.cpp -lboost_system -lpthread -o timer1
Run Code Online (Sandbox Code Playgroud)

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

PS 当我尝试使用使用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")
Run Code Online (Sandbox Code Playgroud)

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

Kik*_*ohs 5

我强烈建议您使用 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 )
Run Code Online (Sandbox Code Playgroud)

在子文件夹 src 中:

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

target_link_libraries( myApp
    ${LIBS_TO_LINK}
)
Run Code Online (Sandbox Code Playgroud)