skip to content

In CMake, how does configure_file turn a version.h.in template into a C++ header that carries the project version?

level: juniorimportance: should knowfreq 55%

answer

  1. a template copied at configure time
  2. @VAR@ and ${VAR} get replaced
  3. project(VERSION) fills PROJECT_VERSION
  4. #cmakedefine and #cmakedefine01
  5. output goes in the build tree

basics

~20 s

configure_file copies the template at configure time, replacing @VAR@ and ${VAR} with CMake variable values and turning #cmakedefine lines into #define or #undef. Put the output in the build tree and add that directory to the target's include path.

solid answer

~40 s

`configure_file(src/version.h.in generated/version.h @ONLY)` copies the template while CMake configures, replacing `@PROJECT_VERSION@` (and, without `@ONLY`, `${VAR}`) with the variable's current value, or an empty string if it is undefined. `project(engine VERSION 2.4.1)` sets `PROJECT_VERSION`, `PROJECT_VERSION_MAJOR` and friends. A line `#cmakedefine ENGINE_WITH_PROFILER` becomes `#define ENGINE_WITH_PROFILER` or `/* #undef ENGINE_WITH_PROFILER */` depending on the variable's truth, and `#cmakedefine01` always defines it as `0` or `1`. A relative output path lands in the current build directory, so you add that directory with `target_include_directories`. CMake re-runs when the template changes and rewrites the output only when its content changed, so an unchanged header does not trigger a rebuild.

code

cmake · 12 lines
cmake
cmake_minimum_required(VERSION 3.25)
project(engine VERSION 2.4.1 LANGUAGES CXX)

option(ENGINE_WITH_PROFILER "Build the frame profiler" ON)
set(ENGINE_MAX_PLAYERS 8)

configure_file(src/version.h.in generated/version.h @ONLY)

add_executable(engine src/main.cpp)
target_compile_features(engine PRIVATE cxx_std_17)
target_include_directories(engine PRIVATE
    ${CMAKE_CURRENT_BINARY_DIR}/generated)

go deeper

for a junior

Recall that configure_file replaces @VAR@ placeholders at configure time and writes the result into the build directory.

for a middle

Explain #cmakedefine versus #cmakedefine01, the effect of @ONLY, and why the output is rewritten only when its content changes.

for a senior

Choose configure-time generation for values known at configure time and a build-time step for values like a commit hash that change without re-configuring.

for a principal

Decide which build facts a team embeds in binaries and keep that generation reproducible, so two builds of one commit give the same header.

## What configure_file does `configure_file(<input> <output> ...)` copies a file and transforms its content on the way. It runs at **configure time**, while CMake processes `CMakeLists.txt`, not while the compiler runs. The usual job is to turn values CMake knows, such as the project version or which options are on, into a header that C++ code can `#include`. Path rules: - A relative `<input>` is relative to `CMAKE_CURRENT_SOURCE_DIR`. - A relative `<output>` is relative to `CMAKE_CURRENT_BINARY_DIR`, so generated files stay in the build tree and the source tree stays clean. - Missing output directories are created. ## The substitution rules The CMake documentation lists what gets replaced in the input: - `@VAR@`, `${VAR}` and `$CACHE{VAR}` are replaced with the variable's current value, or the empty string if it is not defined; `$ENV{VAR}` with the environment variable. - A line `#cmakedefine VAR ...` becomes `#define VAR ...` when `VAR` is set to anything `if()` does not treat as a false constant, and `/* #undef VAR */` otherwise. - A line `#cmakedefine01 VAR` becomes `#define VAR 1` or `#define VAR 0`. Options change this: | Option | Effect | |---|---| | `@ONLY` | Replace only `@VAR@`; leave `${VAR}` alone. | | `COPYONLY` | Copy without any substitution. | | `ESCAPE_QUOTES` | Backslash-escape quotes in substituted values. | | `NEWLINE_STYLE UNIX` | Force the output's line endings. | `@ONLY` is the safe default for C and C++ templates, and essential for shell or CMake scripts, where `${...}` is the template's own syntax. ## A version header, end to end The template `src/version.h.in`: ```cpp #pragma once #define ENGINE_VERSION "@PROJECT_VERSION@" #define ENGINE_VERSION_MAJOR @PROJECT_VERSION_MAJOR@ #define ENGINE_MAX_PLAYERS @ENGINE_MAX_PLAYERS@ #cmakedefine01 ENGINE_WITH_PROFILER ``` `project(engine VERSION 2.4.1 LANGUAGES CXX)` sets `PROJECT_VERSION` to `2.4.1` and the component variables `PROJECT_VERSION_MAJOR`, `PROJECT_VERSION_MINOR` and `PROJECT_VERSION_PATCH`. With `option(ENGINE_WITH_PROFILER ... ON)` and `set(ENGINE_MAX_PLAYERS 8)`, CMake 4.4.4 generated: ```cpp #pragma once #define ENGINE_VERSION "2.4.1" #define ENGINE_VERSION_MAJOR 2 #define ENGINE_MAX_PLAYERS 8 #define ENGINE_WITH_PROFILER 1 ``` Reconfiguring with `-DENGINE_WITH_PROFILER=OFF` changed only the last line to `#define ENGINE_WITH_PROFILER 0`. ## #cmakedefine or #cmakedefine01 - `#cmakedefine` produces a macro that is either **defined or absent**, so C++ code tests it with `#ifdef`. A typo in the `#ifdef` name compiles silently and takes the wrong branch. - `#cmakedefine01` always defines the macro, as `0` or `1`, so code tests it with `#if ENGINE_WITH_PROFILER` or even `if constexpr (ENGINE_WITH_PROFILER)`. With `-Wundef`, a misspelt name in `#if` produces a warning instead of silently meaning 0. Do not use both forms for the same name in one template: both emit a `#define`, and when both are true the compiler warns about a macro redefinition. ## When it runs again 1. The generated build system records the template as a configure dependency: editing `version.h.in` makes the next build re-run CMake. 2. On every configure, the output file is **only modified when its content changes**, so its timestamp stays put and nothing that includes it recompiles unnecessarily. 3. Values that change between builds without a re-configure, such as the current Git commit, are therefore not a good fit for `configure_file`; they need a build-time step that regenerates the header every build. ## Common mistakes - **Generating into the source tree** with an absolute `${CMAKE_CURRENT_SOURCE_DIR}/version.h` output: the file shows up as an untracked change, and two build directories (Debug and Release, or two compilers) overwrite each other's copy. - **Expecting a variable change to reach the header without a configure.** The header changes only when CMake runs; a `-D` passed on the next configure does regenerate it, an edit to a value computed elsewhere at build time does not. - **Leaving `${...}` unprotected** in a template that is really a script, so `configure_file` replaces text that was meant for the script's own interpreter; `@ONLY` prevents it. - **Testing a `#cmakedefine` macro with `#if`**: when the option is on, the line becomes `#define VAR` with no value, and `#if VAR` then fails to compile (Apple clang 21 reports `expected value in expression`). Test it with `#ifdef`, or switch the template to `#cmakedefine01`. ## Wiring it to a target The generated header lives in the build tree, so the target that includes it needs that directory on its include path, usually with `target_include_directories(engine PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated)`. A library that exposes the header to consumers needs `PUBLIC` and, for installation, a separate install rule, because nothing in the source tree contains it.

  • Why is @ONLY recommended even for a C++ header template?
    Without `@ONLY`, `configure_file` also replaces `${VAR}` references, so any `${...}` text in the template, for example in a comment, a string literal or an embedded script snippet, is silently replaced with a value or an empty string. `@ONLY` limits substitution to the explicit `@VAR@` markers, making the template's intent visible.
  • Why can configure_file not stamp the current Git commit into a header reliably?
    It runs only at configure time. A new commit does not re-run CMake by itself, so the header keeps the hash from the last configure. A build-time step, such as a custom target that regenerates the header on every build and rewrites it only when the content changes, keeps the hash current without forcing needless rebuilds.

configure_file is a mail merge: the template is the letter with placeholders, CMake's variables are the address list, and the merge runs once when you configure, not every time someone reads the letter.

  • Thinks configure_file runs at build time on every compile
  • Writes the generated header into the source tree
  • Expects #cmakedefine to emit #define VAR 0 when the option is off
  • Believes an unchanged configure rewrites the header and forces rebuilds
  • Forgets the build directory on the target's include path