Skip to content

Code Formatting

mt82 edited this page Aug 23, 2023 · 1 revision

C++ Coding convention and style

Coding rules exist to improve readability, keep the code base manageable, reduce the cost of maintenance, allow engineers to understand the code quickly, make a software peer review easier and effective.

Proposal: Google Style Guide

The proposal is to adopt the Google formatting style with a couple of exceptions:

  • brace breaking style: attach braces to surrounding context as suggested by Google Style Guide, but break before braces on function, namespace and class definitions;
  • pointer and reference alignment: align pointer '*' and reference '&' to the left, while Google let place the symbol adjacent to either the type or to the variable name.

clang-format

The clang-format command-line utility can be used to automatically reformat a file according to the predefined style. $ clang-format -i -style="{BasedOnStyle: Google, BreakBeforeBraces: Linux, DerivePointerAlignment: false}" file.cpp

How to format all ".c" and ".h" files located in ./libs and ./examples and subfolders

A clang-format configuration file shall be generated in the parent directory. $ clang-format -style="{BasedOnStyle: Google, BreakBeforeBraces: Linux, DerivePointerAlignment: false}" -dump-config > ..clang-format

When the configuration file .clang-format is located in one of the parent directories of the source file (or current directory for stdin), it is automatically loaded by clang-format.

Batch files can be crated to format all source files at once

  • clang-format-all.sh (for Linux) with the following content:
find ./libs ./examples -type f -not -name '*.cmd' -and -name '*.c*' -or -name '*.h*' | xargs clang-format -i --style=file
  • clang-format-all.cmd (for Windows) with the following content:
@echo off
pushd %~p0
FOR %%f in (libs examples) do (
  pushd %%f
  FOR /R %%i in (*.cxx *.cpp *.h *.hpp) do @clang-format -i --style=file %%i
  popd
)

====================================================================

references: