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.
⚠ 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.
- Open your VS Code and press
Ctrl + Shift + P
to open the Command Pallete; - Type 'JSON' and click on the 'Open Settings (JSON):
- 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"
},
🥳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:
- 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 }"
- 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}"
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)