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}


# === example
  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.


Install latest CMake without sudo using

Meson download file