This is a pre-commit hooks repo that integrates C/C++ linters clang-format, clang-tidy, and oclint.
With int main() { int i; return 10; }
in a file, all three linters should fail on commit:
The above uses this .pre-commit-config.yaml
:
---
fail_fast: false
repos:
- repo: https://github.com/pocc/pre-commit-hooks
sha: master
hooks:
- id: clang-format
args: [--style=Google]
- id: clang-tidy
args: [-checks=*, -warnings-as-errors=*]
- id: oclint
args: [-enable-clang-static-analyzer, -enable-global-analysis]
Note that for your config yaml, you can supply your own args or remove the args line entirely, depending on your use case.
You will need to install these utilities in order to use them. Your package manager may already have them.
brew install llvm oclint
apt install clang-format clang-tidy oclint
Bash is required to use these hooks as all 3 invoking scripts are written in it.
What it does | Fix Inplace | |
---|---|---|
clang-format | Formats C/C++ code according to a style | -i |
clang-tidy | clang-based C/C++ linter | -fix, --fix-errors [1] |
oclint | static code analysis tool for C, C++ and Objective-C code | N/A |
[1]: -fix
will fail if there are compiler errors. -fix-errors
will -fix
and fix compiler errors if it can, like missing semicolons.
Some linters change behavior between versions. To enforce a linter version
8.0.0, for example, add --version=8.0.0
to args:
for that linter. Note that
this is a pre-commit hook arg and passing it to the linter will cause an error.
clang-tidy
and oclint
both expect a
compilation database.
Both of the hooks for them will ignore the error for not having one.
You can generate with one cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ...
if you
have a cmake-based project.
Options after --
like -std=c++11
will be interpreted correctly for
clang-tidy
and oclint
. Make sure they sequentially follow the --
argument
in the hook's args list.
To run the tests and verify clang-format
, clang-tidy
, and oclint
are
working as expected on your system, use pytest tests/hooks_test.py --runslow
.
- Official Docs
- clang-format Guide - a good overview and a great place to get started
- clang-format Configurator - Website to interactively design your config while
- clang-format Options Explorer - Website to interactively understand various options
- Official Docs
- clang-tidy guide - Good place to start
- Example usage - Explanation of how to use clang-tidy by the creators of Kratos
- Add your own checks - Function names must be awesome!
Apache 2.0