如果我理解实际问题,它基本上是在询问如何在 CMake 中静态链接到 3rd 方库。
在我的环境中,我已将 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)