Clang Format

Installation in Ubuntu

sudo apt install --no-install-recommends clang clang-format

Set up Git Hook

  • copy file git-clang-format to /usr/local/bin

  • copy file pre-commit to .git/hooks of the repository under development

  • generate .clang-format file in the root directory of the project

File: pre-commit

#!/usr/bin/env python

import sys
import subprocess
output = subprocess.check_output(["git", "clang-format", "--diff"])

if output not in ['no modified files to format\n', 'clang-format did not modify any files\n']:
  sys.exit("""Error: clang format check failed. Run git clang-format -f to fix it, then commit again.
NOTE: if (and *only* if) this is a merge commit, you may skip this check with 'git commit -n'""")

File: git-clang-format

File: .clang-format


  • If git hook is set, run the following command before every git commit.

git clang-format -f
  • In addition to being used as a git hook, clang can format a single c++ file in command line.

clang-format -i -style=google *.cpp  # use google default coding style
clang-format -i -style=file *.cpp  # if .clang-format is ready (in the same dir)
  • To disable clang formatting in certain cases.

int formatted_code;
// clang-format off
    void unformatted_code;
// clang-format on
void formatted_code_again;


Official documentation


A script to automatically install clang-format and set up git hook

Last updated