How to automatically download C++ dependencies in a cross platform way + CMake?

In CMake you can use file(DOWNLOAD URL PATH) to download a file, combine this with custom commands to download and unpack:

set(MY_URL "http://...")
set(MY_DOWNLOAD_PATH "path/to/download/to")
set(MY_EXTRACTED_FILE "path/to/extracted/file")

if (NOT EXISTS "${MY_DOWNLOAD_PATH}")
    file(DOWNLOAD "${MY_URL}" "${MY_DOWNLOAD_PATH}")
endif()

add_custom_command(
    OUTPUT "${MY_EXTRACTED_FILE}"
    COMMAND command to unpack
    DEPENDS "${MY_DOWNLOAD_PATH}")

Your target should depend on the output from the custom command, then when you run CMake the file will be downloaded, and when you build, extracted and used.

This could all be wrapped up in a macro to make it easier to use.

You could also look at using the CMake module ExternalProject which may do what you want.


From cmake 3.11 on there is a new feature: FetchContent

You can use it to get your dependencies during configuration, e.g. get the great cmake-scripts.

include(FetchContent)

FetchContent_Declare(
  cmake_scripts
  URL https://github.com/StableCoder/cmake-scripts/archive/master.zip)
FetchContent_Populate(cmake_scripts)
message(STATUS "cmake_scripts is available in " ${cmake_scripts_SOURCE_DIR})

I prefer fetching the ziped sources instead of directly checking out. But FetchContent also allows to define a git repository.