Use Ccache with CMake

Use Ccache with CMake

Compiling large projects can be time-consuming, especially during development iterations. Fortunately, tools like Ccache accelerates the recompilation process by caching previously compiled objects. This particularly useful when frequently transitioning between branches in a source control system. Such transitions often lead to alterations in the contents and/or timestamps of source files. This tutorial demonstrates how to use Ccache with CMake.

The CMAKE_<LANG>_COMPILER_LAUNCHER property provides a convenient way to configure Ccache as a wrapper for compiling the target. By setting this property, we can instruct CMake to use Ccache as the launcher for the C, C++, CUDA and other compilers.

The following CMake script searches for the Ccache executable using find_program and, if found, configures Ccache as the compiler launcher for both C and C++ compilers.

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

find_program(CCACHE_PROGRAM ccache)
if (CCACHE_PROGRAM)
    set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
    set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
    message(STATUS "Ccache found: ${CCACHE_PROGRAM}")
else ()
    message(STATUS "Ccache not found")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

This configuration is applicable for the Unix Makefile and Ninja generators.

Leave a Comment

Cancel reply

Your email address will not be published.