Skip to content
systemcoding.dev
Toolchains

Enforce a Code Style With clang-format

Configure clang-format with a .clang-format file, format files and diffs, and fail CI on unformatted code so style discussions end before review.

6 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the LLVM, GNU and CMake logos.

Style arguments in code review waste time and make no program faster. A formatter ends them by making the decision once, in a configuration file, and applying it mechanically. clang-format is the formatter that ships with LLVM for C, C++, Objective-C, Java, JavaScript, JSON and a few other languages. This post shows how to pick a base style, write the .clang-format file, run it on files and on changed lines only, make your editor format on save, protect the few blocks that should stay hand-formatted, and add a CI check that fails when a commit is not formatted. The examples use clang-format 18.

See it work

Format a deliberately ugly function with the built-in LLVM style:

ugly.cc
#include <stdio.h>
int main(){int x=1;if(x>0){printf("%d\n",x);}for(int i=0;i<3;i++)printf("%d ",i);return 0;}
Shell
clang-format --style=LLVM ugly.c
Text
#include <stdio.h>
int main() {
  int x = 1;
  if (x > 0) {
    printf("%d\n", x);
  }
  for (int i = 0; i < 3; i++)
    printf("%d ", i);
  return 0;
}

Without -i, the formatted text goes to standard output and the file is untouched. With -i the file is rewritten in place. Notice what the tool did and did not do: it put each statement on a line, added spaces around operators and indented by two spaces. It did not add braces around the for body, because formatting never changes the meaning of the program, and it did not move #include lines.

Choose a base style

clang-format has predefined styles, selected with BasedOnStyle: LLVM, Google, Chromium, Mozilla, WebKit, Microsoft and GNU. Most projects pick the nearest one and override a few options. Differences are mostly indentation width, brace placement and the column limit: LLVM and Google use two spaces and 80 columns, Mozilla and WebKit use four spaces, Microsoft uses four spaces and 120 columns, and GNU puts braces on their own line, indented. The Linux kernel's style is not a named base, though the kernel tree ships a .clang-format file that approximates it.

Print what a base style means with --dump-config:

Shell
clang-format --style=LLVM --dump-config | head -n 8
Text
---
Language:        Cpp
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
  Enabled:         false

The output is the full list of every option, which runs to several hundred lines. Use it as a reference to find the name of an option, then write only the differences from the base in your file.

Write the configuration file

Put a file named .clang-format at the root of the repository. clang-format looks for it in the directory of the file being formatted and then in each parent directory, which lets subdirectories override the rules. A typical C project file:

.clang-formatYAML
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
BreakBeforeBraces: Linux
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
PointerAlignment: Right
SortIncludes: CaseSensitive
IncludeBlocks: Regroup

What each line decides: IndentWidth: 4 sets spaces per level. ColumnLimit: 100 wraps lines longer than that; 0 disables wrapping. BreakBeforeBraces: Linux puts the opening brace on the same line for control statements and on its own line for functions, the classic kernel layout. AllowShortFunctionsOnASingleLine: None stops one-line functions. PointerAlignment: Right writes char *p, binding the star to the name. SortIncludes and IncludeBlocks order and group #include lines, which reduces merge conflicts. Check the option reference at clang.llvm.org/docs/ClangFormatStyleOptions.html for each name, because they change between releases.

With the file in place, format with --style=file, which is the default when a .clang-format exists and the explicit spelling is useful in scripts:

Shell
clang-format -i --style=file src/main.c src/util.c

Format only what you changed

Reformatting a whole legacy file creates a huge diff that hides the real change. git clang-format formats only the lines you modified. It ships with Clang as a Python script, and it works on the working tree or on a commit:

Shell
git clang-format            ## format lines changed in the working tree vs HEAD
git clang-format HEAD~1     ## format lines changed since the previous commit
git clang-format --diff     ## show the formatting patch without applying it

A new code base should adopt the formatter once, in one commit that changes nothing else. Record that commit's hash in a .git-blame-ignore-revs file and tell git to skip it with git config blame.ignoreRevsFile .git-blame-ignore-revs, so git blame still shows the real authors. After that, git clang-format keeps new changes in style without touching old lines.

Format on save in the editor

Editors call clang-format through their own integrations. In VS Code, the clangd extension formats with it when you run Format Document, and "Format On Save" is a setting. In Neovim, the language server's formatting handler uses it, or a plugin such as conform.nvim can call the binary. In Vim, :%!clang-format filters the buffer. In CLion, enable the ClangFormat option in the code style settings. When the editor and CI use the same binary version and the same .clang-format, they agree.

Make CI fail on unformatted code

The formatter is only useful if the team cannot skip it. A CI step checks without modifying:

Shell
clang-format --dry-run --Werror $(git ls-files '*.c' '*.h')

--dry-run prints what would change and --Werror makes it exit with a nonzero status if anything would. A failing run prints warnings with the file, line and column of the first difference in each place:

Text
src/main.c:12:19: error: code should be clang-formatted [-Wclang-format-violations]
    int total = a+b;
                  ^

For pull requests it is friendlier to check only changed lines, with git clang-format --diff origin/main, which exits with a status that signals a change. Pin the clang-format version in CI, since the output of the formatter changes between major releases: a new release may reformat things differently and fail every build. Take the same version into the developers' editors, for example by installing clang-format-18 and naming it in the editor settings.

Turn formatting off where it hurts

Some code is better formatted by hand: a table of values aligned by columns, a macro with deliberate line breaks, a generated section. Protect it with comment markers:

c
// clang-format off
static const int lut[4][4] = {
    { 1,  0,  0,  0},
    { 0,  1,  0,  0},
    { 0,  0,  1,  0},
    { 0,  0,  0,  1},
};
// clang-format on

Inside the markers the tool leaves your layout alone. Use them sparingly; they are a sign that an option may do the job, for example AlignArrayOfStructures: Left aligns such tables automatically, and AlignConsecutiveAssignments aligns runs of assignments. A trailing // comment on a line also stops the tool from joining lines in some constructs, a trick for forcing a break.

Pitfalls

  • Version drift. Different major versions format the same code differently. Pin one.

  • Include sorting breaks builds. Some headers must be included in a certain order, such as a platform header before another that depends on it. Use IncludeCategories priorities, or add a blank line between groups, since IncludeBlocks: Preserve keeps blocks and sorts within them.

  • Formatting generated code. Exclude it with a .clang-format-ignore file, supported since Clang 18, listing paths or patterns.

  • Editing the style often. Each change reformats the code base. Decide, commit and leave it.

  • Mixed languages. Use per-language sections in one file, separated by ---, with a Language: key each.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.