Clang - Automate C++ Google Style format using Clang-Format
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:
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:
- On Visual Studio go to Tools » External Tools
- Press the Add button
On the title put Clang (Google Style)
On the command select the path of the clang.bat file. Note that the .clang-format, the ClangFormat.dll and the clang-format.exe should be available on the same directory.
On the arguments put $(ItemPath) 0 0
Check the Use Output window check-box
Now you should have the Clang menu available
Create a keyboard shortcut for CppLint in Visual Studio:
Go to Tools » Options » Environment » Keyboard.
Select Tools.ExternalCommand7. (This assumes Clang (Google Style) is your seventh external command in your Tools menu as shown on the picture above.)
Press a shortcut key Alt+G and Assign it.
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:
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.