Download, verify and extract compressed files with CMake

Using CMake to download and verify the checksum of files is easy and seamless. While this could be done more purely via combinations of add_custom_command() and add_custom_target(), the net effect is the same with the more explicit syntax below. If you don’t use the downloaded file until runtime (e.g. data files used for CI / self-test) then you can put this function download_file() anywhere in CMakeLists.txt.

function(download_file url filename hash_type hash)

if(NOT EXISTS ${filename})
  file(DOWNLOAD ${url} ${filename}
       TIMEOUT 60  # seconds
       EXPECTED_HASH ${hash_type}=${hash}
       TLS_VERIFY ON)
endif()

endfunction(download_file)


# === example
download_file(
  https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg
  ./octo-icon.svg
  SHA1 074e7a34c486d8956562b65a247d908ee097fb07)

This downloads the file and:

  • checks hash signature
  • verifies the SSL certificate

Extract compressed file

CMake also can extract a ZIP file. The internal CMake “tar” command name is universal and OS-agnostic.

Notes

Install latest CMake without sudo using cmake_setup.py.

Meson download file