CMake download and extract compressed files

Using CMake to download, verify the checksum of files and extract compressed files is easy and seamless. FetchContent downloads the file at configure time.

include(FetchContent)

set(CMAKE_TLS_VERIFY true)

function(download_file url hash)

FetchContent_Declare(download_${hash}
URL ${url}
URL_HASH SHA256=${hash}
DOWNLOAD_NO_EXTRACT true
)

FetchContent_MakeAvailable(download_${hash})

endfunction(download_file)

# === example
download_file(
  https://upload.wikimedia.org/wikipedia/commons/9/91/Octicons-mark-github.svg
  12794390cce7d0682ffc783c785e4282305684431b30b29ed75c224da24035b4
)

This downloads the file and:

  • checks hash signature
  • verifies the SSL certificate

CMake uses vendored cURL internally.

Extract compressed file

CMake also can extract compressed files like .zip, .tar.bz2, etc. This command can also specify output directory, extract a subset of files matching a pattern and more.

file(ARCHIVE_EXTRACT INPUT in_file.zip)

Notes

Install latest CMake without sudo using cmake_setup.py.

Meson download file