clang-formatĀ is a tool to automatically format your codebase. When writing code, you should be able to focus on writing the code itself instead of on formatting, but itās very useful to have a single formatting style throughout an entire codebase.
It simplifies understanding the code because you donāt have to get used to the personal style of whoever wrote that code. Even when working on a project by yourself, itās still useful, because your style can change over time. This is somewhat related to the topic discussed in this previous post about You Should Refactor More Than You Think.
When having a tool taking care of all formatting-related tasks, you can be sure that all your code is always uniform.
How to use clang-format
Using the tool is very easy. Most editors have a configurable format-on-save option that allows calling clang-format automatically whenever any changes are made to a file.
My personal preference is š§āš»ļø VSCode with theĀ C/C++ extension, which supports clang-format out of the box.
The only remaining thing to do is to configure clang-format using aĀ .clang-format
Ā file.
An example of my file:
Documentation of the different options can be found here.
Preventing ugly commits with git pre-commit hooks
As an additional safety measure, instead of only relying on a correctly configured editor, it is also possible to add checks before committing code in git using aĀ pre-commit hook.
A pre-commit hook is a script that is executed before the commit is created and prevents any bad commits. This can be easily done by creating aĀ pre-commit file and putting it in the .git/hooks-folder
. Clang-format can also be used to prevent code from being committed when it is not correctly formatted.
An example of my pre-commit file:
apps
and lib
are the code folders in my repository.
Unfortunately, pre-commit hooks are not part of the repository itself, which means that they are not automatically cloned.
Next steps
There are many more tools besides clang-format, such asĀ clang-tidy, which go even further than formatting. Clang-tidy can also check for dangerous coding patterns and even do automatic refactoring based on the AST. Playing around with clang-tidy will be for another post.