我有一个依赖于外部库(例如 SDL)的程序。我希望 CMake 为我处理这种依赖关系,所以我正在研究FetchContent. 据我了解,该模块只是下载源代码,以便在配置时提供有关外部库的信息。例如:
include(FetchContent)
FetchContent_Declare(sdl
GIT_REPOSITORY <...>
)
FetchContent_GetProperties(sdl)
# sdl_POPULATED, sdl_SOURCE_DIR and sdl_BINARY_DIR are ready now
if(NOT sdl_POPULATED)
FetchContent_Populate(sdl)
endif()
Run Code Online (Sandbox Code Playgroud)
然而,在某些时候,我想构建该源代码并将其链接到我的主要可执行文件。如何以“现代 CMake 方式”做到这一点?
作为构建的一部分从源代码构建外部库的推荐方法取决于外部库提供的构建方式。
如果外部库使用 cmake 构建,那么您可以通过 add_subdirectory(${libname_SOURCE_DIR}) 调用将该库添加到您的构建中。这样 cmake 会将外部库构建为子文件夹(“子项目”)。外部lib的文件中CMakeLists.txt会有一些语句。add_library(ext_lib_name ...)为了在您的目标(依赖于外部库的应用程序或库)中 使用外部库,您可以简单地调用target_link_libraries(your_application <PRIVATE|PUBLIC|INTERFACE> ext_lib_name) https://cmake.org/cmake/help/latest/command/target_link_libraries.html
我快速浏览了这个 github 存储库https://github.com/rantoniello/sdl -(如果您指的是另一个库,请告诉我),它实际上看起来像是使用 cmake 构建的,并且允许客户端静态地构建或动态链接它: https: //github.com/rantoniello/sdl/blob/master/CMakeLists.txt#L1688-L1740
所以,理想情况下你的应用程序应该能够做到
add_executable(myapp ...)
target_link_libraries(myapp PRIVATE SDL2-static) // Statically link againt SDL2
Run Code Online (Sandbox Code Playgroud)
由于它们的 CMakeLists.txt 文件SDL2-static带有属性(包括目录、链接器标志/命令),这些属性将自动分配给myapp.
如果外部库无法使用 cmake 构建,则可以尝试使用add_custom_target https://cmake.org/cmake/help/latest/command/add_custom_target.html来构建库。大致如下:
add_custom_target(myExternalTarget COMMAND <invoke the repo's build system>)
Run Code Online (Sandbox Code Playgroud)
然后,您需要通过正确的 cmake 函数自行设置对客户来说很重要的目标属性set_target_properties,target_include_directories...有关如何开始处理此类事情的精彩文章: https: //pabloariasal.github.io/2018 /02/19/是时候做 cmake 了/
| 归档时间: |
|
| 查看次数: |
8940 次 |
| 最近记录: |