Visual Studio Code and Clang-Format

This post is on how to get started with Clang-Format in Visual Studio Code.

Install Clang-Format

To get Clang-Format to run with Visual Studio Code you first need to install clang-format on your system.
On Ubuntu you can do this from the package manager with:

sudo apt install clang-format

Verify by checking the version: (Output from my Kubuntu 22.04 LTS):

clang-format –version
Ubuntu clang-format version 14.0.0-1ubuntu1

For Windows you have to download and install the windows package. Make sure its on the the PATH variable. This will help the Extension find it.

Install Clang-Format Extension

Inside Visual Studio Code we start the installation of the Clang-Format extension by Xaver by hitting Ctrl + P and pasting:

ext install xaver.clang-format

You can now check the Visual Studio Code settings and go to Extensions -> Clang-Format configuration.
The Extension’s README provides further instructions. You can view these by Clicking the Clang-Format Extension inside the Extension View (Ctrl + Shift + X).

To format your code, use the shortcuts or right click and choose one of the formatting options (Document, Selection).
The default shortcuts are Ctrl+Shift+I for Linux, Ctrl+Shift+F for Windows and Shift + Option + F for Mac.

Create a clang-format file

If you want to customize how clang-format should format certain parts of your code (indentation, brackets etc.) you can create a .clang-format file. This file needs to be placed in the project folder or any parent folder.

To create that file, its best to use a configurator. Clang-Power Tools offers the Clang-Format Configurator, but you can as well use one directly from your web browser. I usually use this one.