Clang - Automate C++ Google Style format using Clang-Format

The main goal of the Clang project is to create create a new C, C++, etc front-end for the LLVM compiler.

Clang is an open source project and you can download it here. You even have a clang-format plugin for Visual Studio on that page, however I do not recommend use the Visual Studio plugin once in my tests, at least at the time I did it, it did not work properly with the most current versions of Visual Studio. If you use the executable, you will be able to integrate it anyways by following the information of this post.

I suggest you download the executables and DLLs directly from the LLVM site. Alternatively you can download the executable that will be used on this post on the links below:

Clang-Format Dll Clang-Format Executable

Clang-Format

A very useful subset of Clang called ClangFormat allows you to automatically format your source code following predefined sytles (E.g.: LLVM, Google, Chromium, Mozilla, WebKit, etc). You can also customize your own style by creating a configuration file (.clang-format).

You can create your configuration file from stretch or customize one of the supported style. For example, to create a style file based on the C++ Google Style, you can use the following command:

clang-format -style=google -dump-config > .clang-format

Once you create you formating file, you can use the following batch file and the instructions below to integrate it on Visual Studio:

Batch File (clang.bat):

Configuration on Visual Studio

Put Clang on the External Tools:

http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png
http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png
http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png
http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png

Create a keyboard shortcut for CppLint in Visual Studio:

http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png

Now to use you just need to press Ctrl+G on the document you would like to format. After Clang formats and replace your file, the following message will appear:

http://rogeriodossantos.github.io/MainPage/resources/page/Fail/not_available.png

Press yes to reload the formated file.

Note: If you are using a source control that set the file you want to format as read only (E.g.: Old versions of Team Foundation Server), be sure you check-out the file before using clang.

Written on