This guide explains how to install, configure, and integrate clang-format to enforce a consistent C/C++ coding style across Linux environments (Ubuntu, Fedora) and editors such as VS Code.
Installation
Install clang-format based on your Linux distribution.
Ubuntu / Debian
sudo apt install clang-formatFedora / RHEL
sudo dnf install clang-tools-extraVerify installation:
clang-format --versionGlobal Configuration
Create a global .clang-format file in your home directory. This configuration will be used for all projects unless a project-specific .clang-format exists.
nvim ~/.clang-formatPaste the following configuration:
BasedOnStyle: Microsoft
IndentWidth: 2
TabWidth: 2
UseTab: Never
BraceWrapping:
AfterFunction: true
AfterClass: true
AfterStruct: true
AfterControlStatement: true
AfterNamespace: true
AfterEnum: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: trueWhat this configuration enforces
- Microsoft style as a base
- 2-space indentation (spaces only, no tabs)
- Allman-style braces (opening brace on a new line)
- No single-line functions, even if short
Editor Integration (VS Code)
3.1 Install the Clang-Format extension
- Open Extensions (
Ctrl + Shift + X) - Search for Clang-Format
- Install Clang-Format by xaver
Extension ID:
xaver.clang-format3.2 Required editor settings
Open your settings.json:
Ctrl + Shift + P → Preferences: Open Settings (JSON)Add the following configuration:
{
"editor.formatOnSave": true,
"[c]": {
"editor.defaultFormatter": "xaver.clang-format"
},
"[cpp]": {
"editor.defaultFormatter": "xaver.clang-format"
},
"clang-format.executable": "clang-format",
"clang-format.style": "file",
"clang-format.fallbackStyle": "Microsoft"
}This ensures:
clang-formatis used for both C and C++ files- Formatting automatically happens on Save (
Ctrl + S) - The formatter reads from the
.clang-formatfile
Notes & Best Practices
- A
.clang-formatfile in a project root overrides the global one - No symlinks, no system-wide config copies are required
- Avoid deprecated
_clang-formatfiles - The same setup works across Ubuntu, Fedora, and RHEL
Once configured, Ctrl + S will automatically format your C/C++ code using a consistent, predictable style.
Comments
Loading the discussion…