Skip to content

Commit 7540013

Browse files
authored
docs: add guide on setting up a clang-format pre-commit hook (#63)
## Why cpp-linter-hooks already gets more Google traffic than the action (52 of its 288 repository views in the last 14 days came from Google, against 21 for cpp-linter-action), so people are searching for "clang-format pre-commit hook". The site has no page for that query. This is the second how-to written around a search term, after #62; the two PRs are independent. ## What's in this PR One new post in the Guides category: **Set up a clang-format pre-commit hook for C and C++** (`docs/blog/posts/2026-09-20-clang-format-pre-commit-hook.md`), published at `/blog/2026/09/20/clang-format-pre-commit-hook/` (explicit `slug`, plus a meta `description`). 1. A starter `.clang-format`. 2. Installing pre-commit and adding the hook; `rev` is the hook version, `--version` is the clang-format version (`21` resolves to the newest 21.x wheel, a full version pins it exactly). 3. What the first commit looks like, and why "Failed" means the files were fixed. 4. Formatting only your own code: `exclude`, a `DisableFormat` `.clang-format` in the vendored directory, and `types_or` for CUDA and Protobuf. 5. Existing code bases: reformat once with `.git-blame-ignore-revs`, or format as you go; `git clang-format` mentioned for changed-lines-only. 6. Enforcing the same configuration in CI with `pre-commit run --all-files --show-diff-on-failure`, or review suggestions from cpp-linter-action with `format-review`. 7. A troubleshooting table. 8. When to add the clang-tidy hook. ## Checks - Every command and output in the post was run in a scratch git repository with `rev: v1.6.0` and `--version=21` (resolved to clang-format 21.1.8): the blocked commit and the retry, `exclude`, the per-directory `DisableFormat`, `.cu` and `.proto` formatting via `types_or`, `SKIP=clang-format`, the CI output (pasted verbatim) and `blame.ignoreRevsFile`. - The compile database auto-detection mentioned in the last section was checked against `clang_tidy.py` at v1.6.0. - `mkdocs build --strict` passes locally, and the repository's pre-commit hooks pass on the new file. ## Notes - The post does not recommend `--dry-run`. With the released v1.6.0 the hook reports "Passed" for an unformatted file when `--dry-run` is set, with or without `--Werror`; the fix (cpp-linter/cpp-linter-hooks#257) is on `main` but not in a release yet. Once it is released, a check-only variant can be added to step 6. - There is no link to the clang-tidy guide from #62, because that page does not exist on `main` yet and the strict build would fail. The two posts can be cross-linked in a small follow-up once both are merged.
1 parent 0569232 commit 7540013

1 file changed

Lines changed: 254 additions & 0 deletions

File tree

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
---
2+
date:
3+
created: 2026-09-20
4+
slug: clang-format-pre-commit-hook
5+
description: >-
6+
Set up a clang-format pre-commit hook for C and C++: pin the clang-format version, format only
7+
your own code, reformat an existing code base once, and enforce the same check in CI.
8+
categories:
9+
- Guides
10+
tags:
11+
- clang-format
12+
- cpp-linter-hooks
13+
- pre-commit
14+
authors:
15+
- shenxianpeng
16+
---
17+
18+
# Set up a clang-format pre-commit hook for C and C++
19+
20+
Formatting comments are the cheapest part of a code review to get rid of. A pre-commit hook runs
21+
clang-format on the files in each commit, so badly formatted code never reaches a pull request,
22+
and CI stops failing for a missing space.
23+
24+
With the [pre-commit](https://pre-commit.com/) framework, nobody on the team has to install LLVM,
25+
and everyone gets the same clang-format version.
26+
27+
<!-- more -->
28+
29+
## Step 1: Have a `.clang-format` in the repository
30+
31+
If the project already has one, keep it. If not, start from a built-in style and change as little
32+
as possible:
33+
34+
```yaml title=".clang-format"
35+
BasedOnStyle: Google
36+
ColumnLimit: 100
37+
```
38+
39+
The built-in styles are `LLVM`, `Google`, `Chromium`, `Mozilla`, `WebKit`, `Microsoft` and `GNU`.
40+
`clang-format --style=Google --dump-config` prints every option of a style, and the
41+
[clang-format configurator](https://clang-format-configurator.site/) shows the effect of each
42+
option on sample code.
43+
44+
## Step 2: Install pre-commit and add the hook
45+
46+
pre-commit is a Python tool. Install it once per machine:
47+
48+
```bash
49+
pip install pre-commit # or: pipx install pre-commit, brew install pre-commit
50+
```
51+
52+
Add the hook to the repository:
53+
54+
```yaml title=".pre-commit-config.yaml"
55+
repos:
56+
- repo: https://github.com/cpp-linter/cpp-linter-hooks
57+
rev: v1.6.0
58+
hooks:
59+
- id: clang-format
60+
args: [--style=file, --version=21]
61+
```
62+
63+
- `--style=file` makes clang-format read the `.clang-format` file.
64+
- `--version=21` selects the clang-format version. The hook downloads it as a Python wheel, so a
65+
system LLVM is neither needed nor used. `rev` is the version of the hook, not of clang-format.
66+
`21` means the newest 21.x release (21.1.8 at the time of writing); write `--version=21.1.8` to
67+
pin the exact release.
68+
69+
Then enable it in your clone:
70+
71+
```bash
72+
pre-commit install
73+
```
74+
75+
Every contributor runs `pre-commit install` once after cloning. Put that line in
76+
`CONTRIBUTING.md`.
77+
78+
## Step 3: Commit something
79+
80+
Stage a badly formatted file and commit:
81+
82+
```console
83+
$ git commit -m "add main"
84+
clang-format.............................................................Failed
85+
- hook id: clang-format
86+
- files were modified by this hook
87+
```
88+
89+
"Failed" here means the hook reformatted the file in your working tree and stopped the commit, so
90+
you can look at what changed:
91+
92+
```console
93+
$ git status --short
94+
AM src/main.c
95+
$ git diff # the formatting changes
96+
$ git add src/main.c
97+
$ git commit -m "add main"
98+
clang-format.............................................................Passed
99+
```
100+
101+
Two things to know about the scope:
102+
103+
- Only the files staged for the commit are checked, which keeps the hook fast.
104+
- Those files are formatted completely, not just the lines you changed. Step 5 covers what that
105+
does to old code.
106+
107+
The first run takes a little longer, because pre-commit builds an environment for the hook and
108+
downloads clang-format. Both are cached afterwards.
109+
110+
## Step 4: Format only your own code
111+
112+
By default the hook runs on C and C++ sources and headers. Vendored code should be left alone,
113+
because reformatting it makes every later update a merge conflict. There are two ways to exclude
114+
it.
115+
116+
In the hook configuration:
117+
118+
```yaml title=".pre-commit-config.yaml"
119+
- id: clang-format
120+
args: [--style=file, --version=21]
121+
exclude: ^(third_party|external)/
122+
```
123+
124+
Or with a `.clang-format` inside the vendored directory, which also covers editors and anyone
125+
running clang-format by hand:
126+
127+
```yaml title="third_party/.clang-format"
128+
DisableFormat: true
129+
SortIncludes: Never
130+
```
131+
132+
clang-format also handles CUDA, Protobuf and a few other languages. The hook skips them unless you
133+
widen its file types:
134+
135+
```yaml title=".pre-commit-config.yaml"
136+
- id: clang-format
137+
args: [--style=file, --version=21]
138+
types_or: [c++, c, cuda, proto]
139+
```
140+
141+
## Step 5: Decide what to do with existing code
142+
143+
Because the hook formats whole files, the first person to touch an old file gets a diff where
144+
three lines of logic are buried in three hundred lines of whitespace changes. Pick one of these
145+
before turning the hook on for everyone.
146+
147+
**Reformat once.** This is the better option when you can afford it.
148+
149+
```bash
150+
pre-commit run clang-format --all-files
151+
git commit -am "style: apply clang-format to the whole tree"
152+
git rev-parse HEAD >> .git-blame-ignore-revs
153+
git add .git-blame-ignore-revs
154+
git commit -m "chore: ignore the reformat commit in git blame"
155+
```
156+
157+
`.git-blame-ignore-revs` keeps `git blame` useful: lines are attributed to the commit that last
158+
changed their content, not to the reformat. GitHub's blame view reads the file automatically.
159+
Locally, each clone needs:
160+
161+
```bash
162+
git config blame.ignoreRevsFile .git-blame-ignore-revs
163+
```
164+
165+
Open branches will conflict with the reformat commit, so do it when few pull requests are open,
166+
and announce it. After resolving the conflicts, a branch author runs
167+
`pre-commit run clang-format --files <their files>` to bring the branch in line.
168+
169+
**Format as you go.** Leave the hook on and let files get formatted when somebody touches them.
170+
Ask contributors to put the formatting change in a separate commit from the logic change, so
171+
reviewers can skip it. The code base converges more slowly and the noisy diffs last longer.
172+
173+
To format only the changed lines, use `git clang-format`, which ships with LLVM. It does not run
174+
through the pre-commit framework.
175+
176+
## Step 6: Enforce it in CI
177+
178+
A local hook can be skipped with `git commit --no-verify`, and new contributors may not have run
179+
`pre-commit install`. Run the same configuration in CI:
180+
181+
```yaml title=".github/workflows/pre-commit.yml"
182+
name: pre-commit
183+
on:
184+
pull_request:
185+
push:
186+
branches: [main]
187+
188+
jobs:
189+
pre-commit:
190+
runs-on: ubuntu-latest
191+
steps:
192+
- uses: actions/checkout@v5
193+
- run: pipx run pre-commit run --all-files --show-diff-on-failure
194+
```
195+
196+
When a file is not formatted, the job fails and prints the required change:
197+
198+
```console
199+
clang-format.............................................................Failed
200+
- hook id: clang-format
201+
- files were modified by this hook
202+
pre-commit hook(s) made changes.
203+
If you are seeing this message in CI, reproduce locally with: `pre-commit run --all-files`.
204+
To run `pre-commit` as part of git workflow, use `pre-commit install`.
205+
All changes made by hooks:
206+
diff --git a/src/add.c b/src/add.c
207+
index b9e228e..1f76448 100644
208+
--- a/src/add.c
209+
+++ b/src/add.c
210+
@@ -1 +1 @@
211+
-int add(int a,int b){return a+b;}
212+
+int add(int a, int b) { return a + b; }
213+
```
214+
215+
If you would rather have the fix offered in the pull request, use
216+
[cpp-linter-action](https://cpp-linter.github.io/cpp-linter-action/) with `format-review: true`
217+
and the same `version`. It posts the formatting differences as review suggestions that can be
218+
committed from the browser.
219+
[Moving to cpp-linter](2026-09-12-moving-to-cpp-linter.md) has a complete workflow.
220+
221+
## Troubleshooting
222+
223+
| Symptom | Cause and fix |
224+
| --- | --- |
225+
| The hook "fails" on every commit that needs formatting | It fixed the files and stopped the commit. `git add` them and commit again. |
226+
| Formatting differs between two machines | Someone formats with another clang-format version, for example from an editor plugin or a system package. Point the editor at the same version, for example `pip install clang-format==21.1.8`. See [One clang-format version everywhere](2026-09-12-one-clang-version-everywhere.md). |
227+
| `Could not find any stable versions of clang-format on PyPI` | The hook looks the version up on pypi.org each time it runs, so it needs network access. |
228+
| `Unsupported clang-format version '...'` | There is no wheel for that version. The message lists the available ones. |
229+
| Vendored or generated code gets reformatted | Exclude it; see step 4. |
230+
| One block must keep its manual layout | Wrap it in `// clang-format off` and `// clang-format on`. |
231+
| You need to commit without the hook once | `SKIP=clang-format git commit ...` skips this hook only; `git commit --no-verify` skips all hooks. CI still checks the result. |
232+
233+
## Adding clang-tidy later
234+
235+
The same repository provides a `clang-tidy` hook:
236+
237+
```yaml title=".pre-commit-config.yaml"
238+
- id: clang-tidy
239+
args: [--checks=.clang-tidy, --version=21]
240+
```
241+
242+
clang-tidy needs a `compile_commands.json` to find your headers, which the hook picks up from
243+
`build/` and a few other common directories. It is also much slower than clang-format, because it
244+
parses every header a file includes. We suggest keeping clang-format in the hook and running
245+
clang-tidy in CI.
246+
247+
## Where to go next
248+
249+
- All hook options, including the clang-tidy ones, are in the
250+
[cpp-linter-hooks README](https://github.com/cpp-linter/cpp-linter-hooks#readme). It also
251+
compares the hook with `mirrors-clang-format`, which is a good choice when clang-format is all
252+
you will ever need and you want `rev` to be the clang-format version.
253+
- [One clang-format version everywhere](2026-09-12-one-clang-version-everywhere.md) covers
254+
keeping the hook, CI, editors and Docker images on one LLVM version.

0 commit comments

Comments
 (0)