Field Note

Checking Formatting of C/C++ Code with clang-format

clang-format formatting
Posted on Wednesday, September the 11th 2024
1 min read

clang-format is a tool within the clang ecosystem, that may be used to enforce code styling policies (code formatter).

In addition to applying the desired format, we may also use it to check if a set of files conforms to the code styling policy by running clang-format with a combination of the --dry-run and -Werror flags. E.g. let myfile.cpp

#include <iostream>

auto main() -> int {
 // Note the single space indentation width
 std::cout << "Hello!" << std::endl;
}

and .clang-format

BasedOnStyle: LLVM
IndentWidth: 4

then running clang-format as follows will return with an exit code of 1 alongside a couple of log lines reporting formatting errors:

clang-format --style=file --dry-run -Werror myfile.cpp

The essential parts of the call are:

  1. --style=file: tells clang-format to look for the closest .clang-format file and check for the policies declared in it;
  2. --dry-run: does not apply formatting fixes for the configured policies; and
  3. -Werror: reports style policy violations as errors instead of warnings and returns a non-zero exit code in case there are errors.
friedrichkurz.me

© 2025 Friedrich Kurz

Privacy Policy