对于位于例如 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/