Build caching with ccache

I recently setup ccache to speed up our build in local development, and I’d like to enable it on CircleCI as well.

Initially adding this to our config worked:
- run:
name: Ensure ~/ccache directory exists
command: mkdir -p ~/.ccache
- restore_cache:
keys:
- persistent_ccache_v2

- save_cache:
paths:
- ~/.ccache
key: persistent_ccache_v2

However, I was not aware that caches are immutable at that point. As a result, the cache ends up becoming useless as the code changes.

I tried to setup a daily cache like this instead:
- run:
name: Ensure ~/ccache directory exists
command: mkdir -p ~/.ccache
- run:
name: Create daily cache key
command: echo “export CACHE_KEY=$(date --iso-8601)” >> $BASH_ENV
- restore_cache:
keys:
- ccache_{{ .Environment.CACHE_KEY }}

- save_cache:
paths:
- ~/.ccache
key: ccache_{{ .Environment.CACHE_KEY }}

Unfortunately that doesn’t work either because that environment variable is neither exported by CircleCI or setup within a context: the key ends up being “ccache_”.

Any ideas on how to make this work?

I have had limited success the time or two I’ve wanted to do something similar.

From what I remember, there is a workaround, which would be to have a step that touches a file with a datestamp, then use the {{ checksum "the_file" }} as your cache key.

For example:

In your case, you’d put the datestamp in the contents of the file.

There’s a support article that suggests more or less exactly this for your use case:

Ah, that’s a clever workaround. Thanks!

1 Like