Skip to main content

pre-commit hooks

PyPI - Python Version PyPI version CI Build CodeQL pre-commit.ci status CodeFactor Quality Gate StatusCodacy Badge

This is a pre-commit hooks repo that integrates C/C++ linters/formatters to work with CMake-based projects.

clang-format, clang-tidy, cppcheck, cpplint, lizard and iwyu

It is largely based on the work found here. The main difference with POCC's pre-commit hooks is that the ones from this repository will do a CMake configuration step prior to running any pre-commit hooks. This is done in order to have CMake generate the compilation database file that can then be used by the various hooks (using the -DCMAKE_EXPORT_COMPILE_COMMANDS=ON CMake option).

This repository is only has Python-based pre-commit hooks.

Current known issues

  1. Currently, the hooks that depend on having a compilation database generated by CMake (e.g. clang-tidy, cppcheck) are not working on Windows if you are not using the Ninja or Makefile generators.

Example usage

Assuming that you have the following directory structure for your projects

root
├── .pre-commit-config.yaml
├── CMakeLists.txt
└── src
    └── err.cpp

with the following file contents:

.pre-commit-config.yaml

repos:
  - repo: https://github.com/Takishima/cmake-pre-commit-hooks
    rev: v1.8.0
    hooks:
      - id: clang-format
      - id: clang-tidy
        args: [--checks=readability-magic-numbers,--warnings-as-errors=*]
      - id: cppcheck
      - id: include-what-you-use

CMakeLists.txt

cmake_minimum_required(VERSION 3.15)
project(LANGUAGE CXX)
add_library(mylib STATIC src/err.cpp)

src/err.cpp

#include <string>
int main() { int i; return 10; }

Running pre-commit on the above project will lead to an output similar to this one:

$ pre-commit run --all-files
clang-format.............................................................Failed
- hook id: clang-format
- exit code: 1

src/err.cpp
====================
<  int main() { int i; return 10; }
---
>  int main() {
>    int i;
>    return 10;
>  }

clang-tidy...............................................................Failed
- hook id: clang-tidy
- exit code: 1

/tmp/temp/src/err.cpp:2:28: error: 10 is a magic number; consider replacing it with a named constant [readability-magic-numbers,-warnings-as-errors]
int main() { int i; return 10; }
                           ^

cppcheck.................................................................Failed
- hook id: cppcheck
- exit code: 1

/tmp/temp/src/err.cpp:2:18: style: Unused variable: i [unusedVariable]
int main() { int i; return 10; }
                 ^
include-what-you-use.....................................................Failed
- hook id: include-what-you-use
- exit code: 1

Problem with /usr/local/bin/iwyu_tool.py: Include-What-You-Use violations found

/tmp/temp/src/err.cpp should add these lines:
/tmp/temp/src/err.cpp should remove these lines:
- #include <string>  // lines 1-1
The full include-list for /tmp/temp/src/err.cpp:
---

Note that your mileage may vary depending on the version of the tools. The example above was generated using clang-format 12.0.0, clang-tidy 12.0.0, cppcheck 2.4.1 and include-what-you-use 0.16.

Using the Hooks

Python 3.10+ is required to use these hooks, as all of them are written in Python.

Running multiple hooks in parallel is currently supported by using the fastener Python package. If the hooks are run in parallel, only one of the hooks will run the CMake configure step while the others will simply wait until the call to CMake ends to continue. In the case where the hooks are run serially, all the hooks will be running the CMake configure step. However, if nothing changed in your CMake configuration, this should not cost too much time.

Installation

For installing the various utilities, refer to your package manager documentation. Some guidance can also be found here.

Hook Info

Hook Info Type Languages
clang-format Formatter C, C++, ObjC
clang-tidy Static code analyzer C, C++, ObjC
cppcheck Static code analyzer C, C++
cpplint Static code analyzer C, C++
include-what-you-use Static code analyzer C, C++
lizard Code complexity analyzer C/C++, ObjC, ...

Hook options

Since v1.1.0 all hooks that depend on a compilation database (e.g. clang-tidy, cppcheck, include-what-you-use) will attempt to generate a CMake build directory before running the actual command.

These hooks accept all the most common CMake options:

CMake options Description
-S <path-to-source> Explicitly specify a source directory.
-B <path-to-build> Explicitly specify a build directory.
-D <var>[:<type>]=<value> Create or update a cmake cache entry.
-U <globbing_expr> Remove matching entries from CMake cache.
-G <generator-name> Specify a build system generator.
-T <toolset-name> Specify toolset name if supported by generator.
-A <platform-name> Specify platform name if supported by generator.
--preset <preset> Specify a configure preset.
-Wdev Enable developer warnings.
-Wno-dev Suppress developer warnings.
-Werror=dev Make developer warnings errors.
-Wno-error=dev Make developer warnings not errors.

One important thing to note (particularly for those that intend to use this on CIs), you may specify the build directory argument (-B) multiple times. The hooks will then simply cycle through all of the values provided and choose the first directory that contains a configured CMake project (by looking at the presence of the CMakeCache.txt file). This may be useful if you already have a build directory available somewhere that you would like to reuse. In the case where none of the provided options is viable, the first one will automatically be selected as the build directory.

In addition to the above CMake options, the hooks also accept the following:

Other hook options Description Note
--all-at-once Pass all filenames to the command at once Since v1.4.0
--clean Perform a clean CMake build Since v1.4.0
--cmake Specify path to CMake executable Since v1.4.0
--cmake-build-target Build a CMake target after the configure step Unreleased
--codegen Build the CMake codegen target (CMake >= 3.31) Unreleased
--detect-configured-files Enable cmake tracing and detection of configured files Since v1.9.0
--dump-toml Dump the current configuration as TOML on stdout Since v1.9.0
--hooks-config Path to a TOML configuration file Unreleased
--no-automatic-discovery Disable automatic build directory discovery Since v1.9.0
--no-cmake-configure Do not call CMake configure Since v1.9.2
--read-json-db Append file list from compile database Since v1.7.0
--require-version Fail unless the tool version starts with this value Unreleased
--version Show the version of the hooks and exit Unreleased
--linux Linux-only CMake options Since v1.3.0
--mac MacOS-only CMake options Since v1.3.0
--win Windows-only CMake options Since v1.3.0

NB: by specifying --all-at-once the linter/formatter command will only be called once for all the files instead of calling the command once per file.

NB: --require-version=18.1 makes a hook fail unless the version of its tool starts with 18.1. If the version matches, the hook then runs as usual.

Breaking change (unreleased): the version check was renamed from --version to --require-version (version to require_version in TOML files), and a hook no longer stops after a successful check. --version now shows the version of the hooks:

# Before
args: [--version=18.1]
# After
args: [--require-version=18.1]

NB: the cpplint hook accepts the same options and TOML configuration as the other hooks (unreleased).

NB: Since v1.6.0, the --debug command line argument has been removed. Use the LOGLEVEL environment variable instead to control the level of verbosity of each of the commands. To show all debug messages, set LOGLEVEL=DEBUG in your environment variables when running the hooks.

NB: by specifying --read-json-db the hook will read the list of files from the compile_commands.json generated by CMake and will append those files to the list of files to process regardless of the list of files otherwise passed on the command line.

NB: by specifying --no-cmake-configure the hook will not attempt to create a compilation database by using CMake. However, if one is present, then it will be used by the relevant hooks.

NB: by specifying --cmake-build-target <name> (may be repeated) the hook will build the given CMake target(s) right after the CMake configure step and before running the actual command. This is useful if some of your source files are generated at build time (e.g. using add_custom_command(...)) and need to exist for the hooks to work properly.

NB: --codegen is a shorthand for --cmake-build-target codegen, which builds the codegen target provided by CMake in order to run all the custom commands marked with the CODEGEN keyword. This requires CMake 3.31 or newer, a Ninja or Makefile generator and the policy CMP0171 set to NEW in your project (e.g. using cmake_minimum_required(VERSION 3.31)). The hooks will check the CMake version and the generator and exit with an error if they do not support the codegen target. With older versions of CMake, use --cmake-build-target with one of your own targets instead.

NB: the hooks will use the CMake found on your system if there is one. If no CMake executable can be found when the hooks are installed, CMake (>= 3.31) will be installed automatically from PyPI inside the environment of the hooks.

Usage example:

repos:
- repo: https://github.com/Takishima/cmake-pre-commit-hooks
  rev: v1.8.0
  hooks:
    - id: cppcheck
      args: [-DBUILD_TESTING=ON,
             --unix="-DCMAKE_CXX_COMPILER=g++-10",
             --win="-DCMAKE_CXX_COMPILER=cl.exe"
             -Bpath/to/build_dir,
             -Bpath/to/other_build_dir,
             -Spath/to/src_dir
             ]

In the example above, the any hooks requiring a compilation database will first search for a build directory path/to/build_dir and then path/to/other_build_dir. If any of those is deemed valid (ie. is a CMake build directory that contains some CMake cache files), then it will be used. If none qualify, the hooks will default to using path/to/build_dir as a build directory, creating it as necessary.

Also, builds on Linux and MacOS will set the C++ compiler to g++-10, while builds on Windows will be using cl.exe. This is done by looking at the value returned by platform.system().

TOML support

Since v1.9.0, the hooks support loading the CLI arguments from TOML files. This can be used to configure the hooks for a particular repository using either of:

  1. pyproject.toml (under tool.cmake_pc_hooks section)
  2. cmake_pc_hooks.toml
  3. TOML file specified using --hooks-config=/path/to/file.toml
  4. Command line arguments

Note that each step in the above list is overridden by the steps that happen after it. For example, CLI arguments will always override any arguments read from any TOML file.

Breaking change (unreleased): the option to specify a TOML file was renamed from --config to --hooks-config. --config is now passed on to the underlying tool (e.g. clang-tidy --config=...):

# Before
args: [--config=hooks.toml]
# After
args: [--hooks-config=hooks.toml]

An option that is not known to the hooks, or a value of the wrong type, is an error.

Settings for a single hook

Settings placed in a table named after a hook only apply to that hook, and override the common ones from the same file. The table names are the hook names: clang-format, clang-tidy, cppcheck, cpplint, include-what-you-use and lizard.

In pyproject.toml:

[tool.cmake_pc_hooks]
build_dir = ["build"]

[tool.cmake_pc_hooks.clang-tidy]
all_at_once = true

In cmake_pc_hooks.toml (or a file passed with --hooks-config):

build_dir = ["build"]

[clang-tidy]
all_at_once = true

Creating a TOML file

A good place to start if you plan on creating a TOML configuration file is to use the hooks using the CLI arguments as you would normally and then run the hook manually and with the addition of --dump-toml. This will output a TOML-formatted configuration on the standard output for all the parameters that were set, either on the command line or in a TOML file.

For example, running the following command (assuming that no valid TOML configuration exists):

cmake-pc-clang-format-hook tests/cmake_bad/bad.cpp --dump-toml -B /tmp/build -S tests/cmake_bad -Wdev --no-automatic-discovery

will result in the following output:

source_dir = "tests/cmake_bad"
build_dir = ["/tmp/build"]
dev_warnings = true
automatic_discovery = false

CMake configured file detection

Since v1.9.0, the hooks support the use of CMake with trace mode enabled in order to keep track of files that are generated using calls to the configure_file(...) CMake function. If --detect-configured-files is specified on the command line (or in some TOML configuration file), the hooks will attempt to locate those generated files and automatically add them to the list of processed files for any hook invocation.

Hook Option Comparison

Hook Options Fix In Place Enable all Checks Set key/value
clang-format -i
clang-tidy --fix-errors 1 -checks=* -warnings-as-errors=* 2
cppcheck -enable=all
include-what-you-use

The '--' doubledash option

Options after -- like -std=c++11 will be interpreted correctly for clang-tidy. Make sure they sequentially follow the -- argument in the hook's args list.

Standalone Hooks

If you want to have predictable return codes for your C linters outside of pre-commit, these hooks are available via PyPI. Install it with pip install cmake-pre-commit-hooks. They are named as cmake-pc-$cmd-hook, so clang-format becomes cmake-pc-clang-format-hook.

Running the tests

The unit tests only require the Python test dependencies:

python -m pip install -e .[test]
python -m pytest

The integration tests run the hooks for real, on copies of the projects found in tests/cmake_good and tests/cmake_bad. They require CMake as well as the linters (and pre-commit for the end-to-end tests):

python -m pytest tests/integration

Each test works on its own temporary copy of the projects, so they can safely be run in parallel using pytest-xdist (installed as part of the test extra), which is about 2.5 times faster on a 4-core machine:

python -m pytest tests/integration -n auto

Tests that require a tool that is not installed are skipped. Use --required-tools to make them fail instead, e.g. --required-tools=all or --required-tools=cmake,clang-format,clang-tidy.

  1. -fix will fail if there are compiler errors. -fix-errors will -fix and fix compiler errors if it can, like missing semicolons. ↩

  2. Be careful with -checks=*; some checks can have self-contradictory rules in newer versions of LLVM (9+). For example, modernize wants to use trailing return type but Fuchsia disallows it. ↩

Metadata

Release files for cmake-pre-commit-hooks 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cmake-pre-commit-hooks 2.0.1
File Size Uploaded Provenance Actions
cmake_pre_commit_hooks-2.0.1.tar.gz 87.3 kB With provenance Details for cmake_pre_commit_hooks-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cmake-pre-commit-hooks 2.0.1
File Interpreter ABI Platform Actions
cmake_pre_commit_hooks-2.0.1-py3-none-any.whl Python 3 none any Details for cmake_pre_commit_hooks-2.0.1-py3-none-any.whl

Total release size: 126.6 kB

Release files / cmake_pre_commit_hooks-2.0.1.tar.gz

Download URL cmake_pre_commit_hooks-2.0.1.tar.gz
Size 87.3 kB
Tags Source
SHA-256 checksum
How to use checksums
60dd9c90db4ef6846ef7106629a8893e6ae7a40791421fd02c36ece2af258763
BLAKE2b-256 checksum
How to use checksums
c98892de2a7eab39f1fb443044f5878ddad4b9d9cc0abfb5592073d80e37d1d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / cmake_pre_commit_hooks-2.0.1-py3-none-any.whl

Download URL cmake_pre_commit_hooks-2.0.1-py3-none-any.whl
Size 39.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9715118ce8cba2cb444f2236640cdba05da538b4653060a93da7d4590fdc0cc4
BLAKE2b-256 checksum
How to use checksums
e19a42572fe958878ed4d781ebd06f47044f51c32a9106e92c5e608c32451f89
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Security for cmake-pre-commit-hooks 2.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cmake_pre_commit_hooks-2.0.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page