使用CMake为Boost设置链接器标志

4
我正在尝试编译来自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 当我尝试使用使用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")

我也遇到了与上述相同的错误。

2个回答

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 )

在子文件夹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 可执行文件 server CMakeFiles/server.dir/server.cpp.o: 在函数 __static_initialization_and_destruction_0(int, int)' 中: server.cpp:(.text+0x810): 对 boost::system::generic_category()' 未定义的引用[...]collect2: ld 返回了状态 1 make[2]: *** [server] 错误 1 make[1]: *** [CMakeFiles/server.dir/all] 错误 2 make: *** [all] 错误 2 - ducin
1
@tkoomzaaskz 这个错误通常意味着你正在使用纯C (gcc)编译器链接 C++ 可执行文件。我不知道如何告诉 CMake 应该使用 g++ 而不是 gcc。一个可能的解决方法是将 -lstdc++ 添加到 LINKER_FLAGS 列表中,但我建议只在找不到正确的 g++ 解决方案时使用它。 - Employed Russian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接