How to Format C/C++ Code in VSCode on Windows and Linux
Since the day that Microsoft released Visual Studio Code, I had installed it on Windows instead of notepad++. Because VS Code does not have a built-in code formatter or beautifier by default, I was eager to see a more powerful VS Code with extensions. Now there it is. We can find many useful extensions on Visual Studio Marketplace. Recently I was writing C/C++ code on Ubuntu and found the extension Clang-Format for beautifying C/C++ code. Let’s take a glimpse of how to make clang-format works with Visual Studio Code on Windows and Linux.
Getting Started with Clang-Format
To install an extension, we can press Ctrl+Shift+P and type in “install extension”. When all extensions listed, search for “format”, and you will see the Clang-Format: After installing the extension, you need to restart VSCode.
If you do not have Clang-Format installed on your system, you will see the prompt:
The 'clang-format' command is not available. Please check your clang.formatTool user setting and ensure it is installed.
How to Install Clang-Format on Windows
Install the package and add the path of %LLVM% \bin to your system environment.
The shortcut Alter+Shift+F now works in Visual Studio Code for Windows.
How to Install Clang-Format on Ubuntu 14.04
If you choose to install clang-format-3.4, the VS Code extension can’t work instantly. It will still prompt you that no clang-format found. Why? The installed clang-format tool is named clang-format-3.4:
$ whereis clang-format-3.4 clang-format-3: /usr/bin/clang-format-3.4 /usr/bin/X11/clang-format-3.4
To make it work, you just need to create a symlink:
sudo ln -s /usr/bin/clang-format-3.4 /usr/bin/clang-format
Similarly, create a symbolic link for clang-format:
sudo ln -s /home/xiao/clang+llvm-3.7.0-x86 _64-linux-gnu-ubuntu-14.04/bin/clang-format /usr/bin/clang-format
Now, you can format code with Ctrl+Shift+I in Visual Studio Code for Linux.