简体   繁体   中英

Including external header library from github using cmake

There is an GitHub repository that contains only hpp files with no CMakeList.txt file.

I need to include those header files in my project. I do not want to manually clone them then linking against them. I want that each time I call cmake command, cmake will clone them and put them in some inner folder.

Is it possible? if yes, how can I achive this?

You may want to consider the approach used in the DownloadProject github project which includes an example that does a download step for the GoogleTest repo. It invokes CMake's ExternalProject module during the configure stage rather than the build stage, so the external sources become available at configure time, which seems to be what you want here too. In your case, you don't need the subsequent step of using add_subdirectory() to pull anything from the external project into your main build, so just the download is enough. This approach is also referenced by this answer .

Using DownloadProject looks something like this (taken from the example provided as part of the github project):

include(DownloadProject.cmake)
download_project(PROJ           googletest
                 GIT_REPOSITORY https://github.com/google/googletest.git
                 GIT_TAG        master
)

The downloaded source would then be available under the directory stored in the variable ${googletest_SOURCE_DIR} . See the fully general implementation in the DownloadProject source for how it works. You can simply embed it in your own project's sources and re-use it to efficiently handle downloading any external dependencies you might need.

I managed to do it like this:

file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/external_includes)
execute_process(
    COMMAND git clone "xxxxx.git" lib_name
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/external_includes)

include_directories(${CMAKE_CURRENT_BINARY_DIR}/external_includes)

This approach was tested on Windows with MSVS & Ubuntu with GCC.

Of course, using something like Hunter or any packages manger is preferable but sometimes fast and easy solution are needed.

another option I've spotted at json cpp repo:

FetchContent_Declare(json
    GIT_REPOSITORY https://github.com/nlohmann/json.git
    GIT_TAG v3.7.3)

FetchContent_GetProperties(json)
if(NOT json_POPULATED)
    FetchContent_Populate(json)
    add_subdirectory(${json_SOURCE_DIR} ${json_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()

IMHO looks even better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM