Skip to content

Code format

Arnaud Sevin edited this page Mar 31, 2020 · 4 revisions

Code Style

Recommended code style (using astyle notations) :

  • -A1: Allman style uses broken braces.
  • -s4: 4 space indent
  • -U: Remove unnecessary space padding around parenthesis..
  • -p: Insert space padding around operators.
  • -j: Add braces to unbraced one line conditional statements.
  • -xC80 : maximum 80 char per line
  • -xG: Indent 'class' and 'struct' access modifiers, 'public:', 'protected:' and 'private:', one half indent.
  • -S: Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block. The entire case block is indented.
  • -k3: Attach a pointer or reference operator (*, &, or ^) to the variable name (right).

Code style can be achieved with the astyle command :

astyle -A1 -s4 -U -p -j -xC80 -xG -S -k3

Can also be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

To set up as a github pre-commit hook, create/edit file .git/hooks/pre-commit : (don't forget to add exec permission)

#!/bin/bash

ASTYLEOPTIONS="-A1 -s4 -U -p -j -xC80 -xG -S -k3"

RETURN=0

ASTYLECMD=$(which astyle)
if [ $? -ne 0 ]; then
	echo "[!] astyle not installed. Unable to check source file format policy." >&2
	exit 1
fi

FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h)$")
for FILE in $FILES; do
	$ASTYLECMD $ASTYLEOPTIONS $FILE -n
done

exit $RETURN

Note that clang-format, uncrustify may also be configured accordingly.