DEV Community

Cover image for Format C/Cpp files automatically on VS Code
Thiago Silva Lopes
Thiago Silva Lopes

Posted on

Format C/Cpp files automatically on VS Code

The year is 2022, you're already know some things about programming and your college is teaching you logics with Cpp.

The recommended IDE that they show you is something too to even bother to look, so okay, let's code this on VS Code.

Cat Typing GIF

⚠ The problem

You got everything set up and looking great with the compiler and VS extensions, but as you begin to code you notice that your code isn't formatting itself.

You already got Prettier + ESLint working fine, but they don't offer support C/Cpp. So, how do i format only C/Cpp code with another formatter?

βœ” The solution

Searching around the web i found out that the VS Code C/Cpp support extension already comes with clang-format.

That being said, we doesn't need to install any other thing than the spoken extension, to make our code indent automatically and customize how that formatting is gonna be.

  1. Open your VS Code and press Ctrl + Shift + P to open the Command Pallete;
  2. Type 'JSON' and click on the 'Open Settings (JSON): VS Code Options Screenshot
  3. With the VS Code settings.json open, we can make clang-format as our default formatter (for C/Cpp language only), adding the following code:


"[c]": {
    "editor.defaultFormatter": "ms-vscode.cpptools"
    //☝🏼 Select the MS extension as defaultFormatter
  },
  "[cpp]": {
    "editor.defaultFormatter": "ms-vscode.cpptools"
  },


Enter fullscreen mode Exit fullscreen mode

πŸ₯³That's it! Your code will now auto format! πŸŽ†πŸ™Œ
But... How i customize this? πŸ€”

🎨 Custom your formatting

Clang-format has a lot of options for your format your code the way your prefer more. You can check their documentation in this πŸ‘‰πŸ½ link to see all the options you have.

How to set this options on your VS Code:

  1. Follow the same steps as above to open your settings.json, and put your options inside this code:


"C_Cpp.clang_format_fallbackStyle": "{optionOne: true, optionTwo: 2 }"


Enter fullscreen mode Exit fullscreen mode
  1. All the options needs to be inside this quotes, so you can't format this object in more lines than 1. Even if it is an object.

This are the configs that I find the best for my use:



"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 3, IncludeBlocks: Merge, IndentGotoLabels: true, KeepEmptyLinesAtTheStartOfBlocks: true}"


Enter fullscreen mode Exit fullscreen mode

If you wanna check the settings i use on my VS Code & Terminal, you can check my πŸ‘‰πŸ½ repos on GitHub! 😊

πŸ‘¨πŸ»β€πŸ’» Special thanks & credits to:

Other devs on Stack Overflow who faced the same problem &/or helped to find solutions. ✌🏼

Top comments (0)