How do I format C++ sources with clang-format?
Table of Contents
Style settings, rationale, and examples are in C++ code style: clang-format configuration.
Question
How do I reformat C++ source files, or check whether they are already correctly formatted?
Answer
Reformat in-place
Runs clang-format -i on all .cpp, .hpp, and .h files under
projects/. Use before opening a PR or after pulling a config change.
cmake --build --preset linux-clang-debug-make --target format
Check for drift (dry run)
Reports files that differ from the canonical style and exits non-zero if any file would change. Does not modify files.
cmake --build --preset linux-clang-debug-make --target check-format
Run clang-format directly on one file
Useful for inspecting what the formatter would do to a single file before committing to a full pass:
clang-format --dry-run --Werror projects/ores.iam/api/include/ores.iam.api/domain/account.hpp
Replace --dry-run --Werror with -i to reformat in-place.
Script
Both format and check-format are CMake custom targets defined in
the top-level CMakeLists.txt inside the if (CLANG_FORMAT_FOUND)
block. They use find -exec {} + to collect files and pass them to
CLANG_FORMAT_BIN (resolved by FindClangTools.cmake, which searches
versions 20 down to 5.0). If clang-format is not installed, both
targets are absent and CMake prints a warning at configure time.
Tested by
The nightly nightly-format GitHub Actions workflow runs
clang-format-18 on Ubuntu 24.04 every night at 02:00 UTC and raises
a PR if any file drifts. A clean nightly pass (no PR raised) confirms
the tree is in sync.
See also
- C++ code style: clang-format configuration — every setting with rationale and examples.
- CMake recipes — full list of CMake targets.