使用cmake和Boost.asio?

5
我想将boost.asio静态链接到我的小项目中,不使用外部库(只有一个单独的exe/bin文件来分发)。Boost.asio需要Boost.system,并且我开始陷入困境,尝试弄清楚如何编译所有这些内容。如何在cmake中使用Boost.asio?

所有的boost组件都可以静态链接。你还有什么问题吗? - Jan Hudec
我已经多次在Google上搜索了,每次都发现一些问题,导致我无法编译它。因此,我提出了如何确切地做到这一点的问题。我无法使用cmake编译boost的任何部分,也不知道如何在我的项目中静态地使用它。 - Fedcomp
2
请查看FindBoost.cmake的内容。您可以在CMake安装的Modules/目录中找到它。 - arrowd
1个回答

12

如果我正确理解问题,它基本上是在询问如何在CMake中使用静态链接第三方库。

在我的环境中,我已经将Boost安装到/opt/boost目录下。

最简单的方法是使用CMake安装提供的FindBoost.cmake文件:

set(BOOST_ROOT /opt/boost)
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost COMPONENTS system)

include_directories(${Boost_INCLUDE_DIR})
add_executable(example example.cpp)
target_link_libraries(example ${Boost_LIBRARIES})

一种变体,可以找到所有的 Boost 库并明确链接到系统库:

set(BOOST_ROOT /opt/boost)
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost REQUIRED)

include_directories(${Boost_INCLUDE_DIR})
add_executable(example example.cpp)
target_link_libraries(example ${Boost_SYSTEM_LIBRARY})

如果您没有正确的Boost安装,则有两种方法可以静态链接到库。第一种方法是创建一个导入的CMake目标:

add_library(boost_system STATIC IMPORTED)
set_property(TARGET boost_system PROPERTY
  IMPORTED_LOCATION /opt/boost/lib/libboost_system.a 
)

include_directories(/opt/boost/include)
add_executable(example example.cpp)
target_link_libraries(example boost_system)

另一种方法是在target_link_libraries中明确列出库,而不是目标:

include_directories(/opt/boost/include)
add_executable(example example.cpp)
target_link_libraries(example /opt/boost/lib/libboost_system.a)

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