We have already published an article that describes details of the code style in the article:
In this article, we are going to know a tool that formats our code according to the style we want, it is: clang-format.
ClangFormat(clang-format
) is a toolkit that uses LibFormat that formats your code in a variety of ways, including a standalone tool and editor integrations.
To install clang-format
, you just need the collection of tools from LLVM, here in this article there is the procedure downloading the binary and installing it, but you can also use your system’s package manager to get, examples:
Suppose you have this code C++: main.cpp
:
It is formatted the way I like it, but if I wanted to change it to the GNU standard, I would just run the following command:
The output transforms my code in this style:
Very different formatting, right?!
If you want to save to another file:
There are styles available: llvm
, google
, chromium
, microsoft
, webkit
and others.
Examples:
You can also save your preferred style by dumping it into a file named: .clang-format
in the path/directory you are working with. For that run:
Assuming you prefer the
gnu
style.
The file will be similar to the content below and note that you can change the settings as you wish:
The file is much bigger, the
...
refers to that!
If you want to format multiple .cpp
files use wildcard:
The
-i
parameter modifies the file.
And to modify multiple files including header files, use this command as an example:
If you want to include it in your Code Editor/IDE look for the name corresponding documentation. In the case of Vim/Neovim use vim-clang-format.
For more information see clang-format --help
and the official address of clang-format
.
clang llvm cpp clanguage programming