Skip to content

Caching with CPM.cmake and ccache on GitHub Actions

Olivier Le Doeuff edited this page Mar 5, 2022 · 3 revisions

Caching with GitHub Actions

You can use CPM_SOURCE_CACHE on GitHub Actions workflows cache and combine it with ccache, to make your CI faster.

CPM.cmake

You need to set a path on actions/cache to CPM and use the same path on CPM_SOURCE_CACHE. Here we are using ~/cpm-cache:

- name: Set up cache
  id: cache-cpm
  uses: actions/cache@v2
  with:
    path: ~/cpm-cache
    key: ${{ runner.os }}-cpm-${{ hashFiles('**/') }}
    restore-keys: |
      ${{ runner.os }}-cpm-
                  
- name: Build CMake
  run: |
    mkdir build && cd build
    cmake -DCPM_SOURCE_CACHE=~/cpm-cache ..
    make -j2

ccache

To implement ccache to your workflow:

You need to define some environment variable to tell where ccache will put .ccache and additional informations:

env:
  CCACHE_VERSION: 4.6
  CCACHE_BASEDIR: ${GITHUB_WORKSPACE}
  CCACHE_DIR: ${GITHUB_WORKSPACE}/.ccache
  CCACHE_COMPRESS: true
  CCACHE_COMPRESSLEVEL: 6
  CCACHE_MAXSIZE: 400M
  • CCACHE_VERSION is used later in this tutorial in ccache step. To find possible version checkout ccache fork that cristianadam maintain to have easy to download release assets.
  • CCACHE_DIR will be cache in the ccache_cache step. Check ccache documentation for the other environment variable.

You need to install it:

- name: Download ccache
    id: ccache
    shell: cmake -P {0}
    run: |
      set(ccache_url "https://github.com/cristianadam/ccache/releases/download/v$ENV{CCACHE_VERSION}/${β€Š{ runner.os }β€Š}.tar.xz")
      file(DOWNLOAD "${ccache_url}" ./ccache.tar.xz SHOW_PROGRESS)
      execute_process(COMMAND ${CMAKE_COMMAND} -E tar xvf ./ccache.tar.xz)
-  name: Add ccache to PATH
   run: echo "$(pwd)" >> $GITHUB_PATH

Enable ccache support:

- name: Prepare ccache timestamp
    id: ccache_cache_timestamp
    shell: cmake -P {0}
    run: |
    string(TIMESTAMP current_date "%Y-%m-%d-%H;%M;%S" UTC)
    message("::set-output name=timestamp::${current_date}")

- name: ccache cache files
    id: ccache_cache
    uses: actions/cache@v2
    with:
      path: .ccache
      key: ${β€Š{ matrix.config.name }β€Š}-ccache-${β€Š{ steps.ccache_cache_timestamp.outputs.timestamp }β€Š}
      restore-keys: |
        ${β€Š{ matrix.config.name }β€Š}-ccache-

Finally when running your CMake your either need to add:

-D CMAKE_C_COMPILER_LAUNCHER=ccache
-D CMAKE_CXX_COMPILER_LAUNCHER=ccache

or you can have a look at CCache.cmake.

More information on how to set up your CMake to use ccache here. The author also created a complete example : cristianadam/HelloWorld