gotcha: using ccache in Debian package builds
Before I upload packages to Debian, I always do a full build from source under sbuild. This ensures that the package can build from source on a clean environment, implying that the set of build dependencies is complete.
But when iterating on a non-trivial package locally, I will usually build the
package directly on my Debian testing system, and I want to take advantage of
ccache to cache native (C/C++) code compilation to speed
things up. In Debian, the easiest way to enable ccache
is to add
/usr/lib/ccache
to your $PATH
. I do this by doing something similar to the
following in my ~/.bashrc
:
export PATH=/usr/lib/ccache:$PATH
I noticed, however, that my Debian package builds were not using the cache.
When building the same small package manually using make, the cache was used,
but not when the build was wrapped with dpkg-buildpackage
.
I tracked it down to the fact that in compatibility level 13+, debhelper
will
set $HOME
to a temporary directory. For what's it worth, I think that's a
good thing: you don't want package builds reaching for your home directory as
that makes it harder to make builds reproducible, among other things.
This behavior, however, breaks ccache
. The default cache directory is
$HOME/.ccache
, but that only gets resolved when ccache
is actually used. So
we end up starting with an empty cache on each build, get a 100% cache miss
rate, and still pay for the overhead of populating the cache.
The fix is to explicitly set $CCACHE_DIR
upfront, so that by the time $HOME
gets overriden, it doesn't matter anymore for ccache
. I did this in my
~/.bashrc
:
export CCACHE_DIR=$HOME/.ccache
This way, $HOME
will be expanded right there when the shell starts, and by
the time ccache
is called, it will use the persistent cache in my home
directory even though $HOME
will, at that point, refer to a temporary
directory.