c++ - 如何使用 CMake 从版本控制中可移植地获取仅 header 库?

标签 c++ cmake header-only

对于位于例如 github 上的典型 C++ 仅 header 库,位于:https://github.com/username/library_name

具有一个包含 include/library_name 文件夹的目录结构,例如:

  • include/library_name

包含所有库资源。这通常由用户安装到,例如,在 Linux 下:/usr/local/include/library_name

我需要一个 cmake 脚本以便在外部项目中可移植地使用库(跨 Linux、MacOs、BSD、Windows)。

它应该:

  • 查找库是否安装,如果版本超过阈值,则使用安装的库

  • 否则,从github上获取库,配置为外部项目,放到系统include路径下,让项目像安装一样使用。

使用 CMake 实现此目的的正确方法是什么?

最佳答案

我终于让它工作了,这个 FindLibraryName.cmake 尝试找到库,如果找不到,从 github 获取它并将其设置为外部项目:

# Find the Library_Name include directory
# The following variables are set if Library_Name is found.
#  Library_Name_FOUND        - True when the Library_Name include directory is found.
#  Library_Name_INCLUDE_DIRS - The path to where the poco include files are.
# If Library_Name is not found, Library_Name_FOUND is set to false.

find_package(PkgConfig)

# Allow the user can specify the include directory manually:
if(NOT EXISTS "${LIBRARY_NAME_INCLUDE_DIR}")
     find_path(LIBRARY_NAME_INCLUDE_DIR
         NAMES library_name/library_name.hpp 
         DOC "Library_Name library header files"
     )
endif()

if(EXISTS "${LIBRARY_NAME_INCLUDE_DIR}")
  include(FindPackageHandleStandardArgs)
  mark_as_advanced(LIBRARY_NAME_INCLUDE_DIR)
else()
  include(ExternalProject)
  ExternalProject_Add(library_name
    GIT_REPOSITORY https://github.com/username/library_name.git
    TIMEOUT 5
    CMAKE_ARGS -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
    PREFIX "${CMAKE_CURRENT_BINARY_DIR}"
    INSTALL_COMMAND "" # Disable install step, is a header only lib!
    )

  # Specify include dir
  ExternalProject_Get_Property(library_name source_dir)
  set(LIBRARY_NAME_INCLUDE_DIRS ${source_dir}/include)
endif()

if(EXISTS "${LIBRARY_NAME_INCLUDE_DIR}")
  set(Library_Name_FOUND 1)
else()
  set(Library_Name_FOUND 0)
endif()

然后在项目CMakeLists.txt中,添加:

find_package(Library_Name)
include_directories(${LIBRARY_NAME_INCLUDE_DIRS})

您可以将上面的 GIT 替换为 SVN 并提供 svn 存储库的 URL,它也可以正常工作。其他版本控制系统也可用。

关于c++ - 如何使用 CMake 从版本控制中可移植地获取仅 header 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28629084/

相关文章:

c++ - 使用 CMake 生成可重新分发的项目

CMake 拒绝第二个 target_link_libraries 谈论 "keyword"与 "plain"

c++ - 未找到 Windows7 pthread.h

c++ - 如何在自己的仅 header 库中包含升压 header

c++ - 为什么我不能在同一个 MS VS 解决方案中的两个控制台应用程序中使用 C++ Eigen(仅 header 库)?

c++ - 在 C 中声明两个同名的全局变量

c++ - 最大连续子序列——动态规划还是贪心算法?

c++ - 普通 C++ 代码如何应用于 GUI 编程?

c++ - "Multiple definition of"编写仅 header 模板库时出错

c++ - 获取 out_of_range : vector error for c++ but can't figure out why