分享一下我的 clang-format 配置,主要针对嵌入式 C/C++ 项目进行了优化,注重代码可读性和一致性,同时适度限制行宽以提升代码审查体验。配置涵盖了大括号风格、参数换行、对齐规则、空格使用、Tab 和行尾符等多个方面,旨在形成一个清晰、统一的代码风格规范。
我的主要要求
1 行宽限制为可以半个屏幕显示完全,这样优化分屏显示
2 使用Allman风格的大括号,单独占一行,优化阅读体验
3 对Include的头文件排序
4 永不使用Tab字符,统一使用四个空格缩进
5 函数参数分行显示,禁止装箱,提升代码审查体验
6 统一的空格和对齐规则,提升代码一致性和可读性
配置说明
🔧 基本语言配置
| 配置项 |
当前值 |
说明 |
效果 |
Language |
Cpp |
语言类型,也适用于C语言 |
使用C++/C语言的格式化规则 |
Standard |
Latest |
使用最新的语言标准 |
支持最新的语法特性格式化 |
ColumnLimit |
120 |
每行最大字符数 |
超过100字符自动换行 |
📐 对齐配置
| 配置项 |
当前值 |
说明 |
示例 |
AccessModifierOffset |
-2 |
访问修饰符缩进 |
public: 相对类缩进-2个空格 |
AlignAfterOpenBracket |
Align |
开括号后内容对齐 |
参数与开括号对齐 |
AlignConsecutiveAssignments |
true |
连续赋值语句对齐 |
= 号垂直对齐 |
AlignConsecutiveDeclarations |
true |
连续变量声明对齐 |
变量名垂直对齐 |
AlignConsecutiveMacros |
true |
连续宏定义对齐 |
宏名垂直对齐 |
AlignEscapedNewlines |
Left |
续行反斜杠对齐方式 |
反斜杠左对齐 |
AlignOperands |
true |
操作数对齐 |
多行表达式操作数对齐 |
AlignTrailingComments |
true |
尾随注释对齐 |
行尾注释垂直对齐 |
对齐效果示例
连续赋值对齐:
1 2 3 4
| int x = 10; double value = 3.14; char *name = "test";
|
连续声明对齐:
1 2 3 4
| int count; double ratio; Button_t *button;
|
🚫 单行限制配置
| 配置项 |
当前值 |
说明 |
效果 |
AllowShortBlocksOnASingleLine |
Never |
禁止短代码块单行 |
if (x) { y = 1; } → 必须换行 |
AllowShortCaseLabelsOnASingleLine |
false |
禁止短case标签单行 |
case语句必须换行 |
AllowShortFunctionsOnASingleLine |
None |
禁止短函数单行 |
所有函数都必须换行 |
AllowShortIfStatementsOnASingleLine |
Never |
禁止短if语句单行 |
if语句必须换行 |
AllowShortLoopsOnASingleLine |
false |
禁止短循环单行 |
for/while循环必须换行 |
单行限制示例
禁止短if语句单行:
1 2 3 4 5 6 7 8 9
|
if (condition) { action(); }
|
🔄 换行配置
| 配置项 |
当前值 |
说明 |
效果 |
AlwaysBreakAfterDefinitionReturnType |
None |
函数定义返回类型换行 |
返回类型和函数名同行 |
AlwaysBreakAfterReturnType |
None |
函数声明返回类型换行 |
返回类型和函数名同行 |
AlwaysBreakBeforeMultilineStrings |
false |
多行字符串前不换行 |
字符串紧跟赋值符 |
BreakBeforeBraces |
Allman |
大括号换行风格 |
大括号独占一行 |
BreakBeforeBinaryOperators |
None |
二元运算符换行位置 |
运算符在行末 |
BreakBeforeTernaryOperators |
false |
三元运算符换行位置 |
? 和 : 在行末 |
BreakStringLiterals |
true |
允许字符串字面量换行 |
长字符串可以换行 |
大括号风格示例
Allman 风格:
1 2 3 4 5 6 7 8
| void function() { if (condition) { } }
|
📦 参数和装箱配置
| 配置项 |
当前值 |
说明 |
效果 |
AllowAllArgumentsOnNextLine |
false |
禁止所有参数换到下一行 |
参数分行显示 |
AllowAllParametersOfDeclarationOnNextLine |
false |
禁止所有参数换到下一行 |
函数参数分行显示 |
BinPackArguments |
false |
禁止参数装箱 |
每个参数独占一行 |
BinPackParameters |
false |
禁止参数装箱 |
每个参数独占一行 |
参数格式化示例
禁止参数装箱效果:
1 2 3 4 5 6 7 8 9
| function_call( argument1, argument2, argument3 );
|
🔤 缩进配置
| 配置项 |
当前值 |
说明 |
效果 |
IndentWidth |
4 |
缩进宽度 |
使用4个空格缩进 |
IndentCaseLabels |
true |
case标签缩进 |
case相对switch缩进 |
IndentWrappedFunctionNames |
true |
换行函数名缩进 |
换行的函数名缩进 |
TabWidth |
4 |
Tab宽度 |
Tab等于4个空格 |
UseTab |
Never |
不使用Tab |
始终使用空格 |
💰 换行惩罚权重
| 配置项 |
当前值 |
说明 |
作用 |
PenaltyBreakBeforeFirstParameter |
5 |
函数定义换行惩罚 |
降低函数参数换行倾向 |
PenaltyBreakBeforeFirstCallParameter |
5 |
函数调用换行惩罚 |
降低函数调用换行倾向 |
PenaltyBreakAssignment |
10 |
赋值换行惩罚 |
降低赋值运算符换行倾向 |
PenaltyExcessCharacter |
100 |
超出字符惩罚 |
每个超出字符的惩罚值 |
PenaltyReturnTypeOnItsOwnLine |
0 |
返回类型独行惩罚 |
不惩罚返回类型独行 |
🔧 其他格式化配置
| 配置项 |
当前值 |
说明 |
效果 |
PointerAlignment |
Right |
指针星号对齐 |
char *ptr 星号靠近变量名 |
ReflowComments |
true |
重新格式化注释 |
自动调整注释格式 |
SortIncludes |
true |
排序包含文件 |
自动排序#include |
MaxEmptyLinesToKeep |
1 |
最大空行数 |
最多保留1个空行 |
KeepEmptyLinesAtTheStartOfBlocks |
false |
块开始处不保留空行 |
{ 后不允许空行 |
🔺 空格配置
| 配置项 |
当前值 |
说明 |
示例 |
SpaceAfterCStyleCast |
true |
C风格转换后加空格 |
(int) x |
SpaceAfterLogicalNot |
false |
逻辑非后不加空格 |
!condition |
SpaceBeforeAssignmentOperators |
true |
赋值运算符前加空格 |
x = y |
SpaceBeforeParens |
ControlStatements |
控制语句圆括号前加空格 |
if (condition) |
SpacesBeforeTrailingComments |
1 |
尾随注释前空格数 |
code; // comment |
SpacesInParentheses |
false |
圆括号内不加空格 |
function(arg) |
SpacesInSquareBrackets |
false |
方括号内不加空格 |
array[index] |
📋 包含文件优先级
1 2 3 4 5 6 7 8 9 10 11
| IncludeCategories: - Regex: '"*PlatformIO.h"' Priority: -5 - Regex: '"*TextIOTypes.h"' Priority: -4 - Regex: "<[Ww]indows.h>" Priority: -3 - Regex: '<*\/.h>' Priority: -2 - Regex: '"*\/.h"' Priority: 1
|
排序效果:
1 2 3 4 5 6 7 8
| [[include]] "PlatformIO.h" [[include]] "TextIOTypes.h" [[include]] <Windows.h> [[include]] <stdio.h> [[include]] <stdlib.h> [[include]] "button.h" [[include]] "config.h"
|
🎯 项目适配说明
当前配置针对嵌入式C项目优化:
✅ 可读性优先: 大括号独占一行,参数分行显示
✅ 一致性: 自动对齐声明、赋值、注释
✅ 紧凑性: 100列限制,适合代码审查
✅ 规范性: 统一的空格、缩进规则
✅ 维护性: 自动排序包含文件,重新格式化注释
这套配置确保代码风格统一,提高团队协作效率。
配置文件内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
| # ============================================================================= # clang-format 配置文件 - 针对嵌入式C/C++项目优化 # =============================================================================
## 基础语言配置
Language: Cpp # 指定语言类型,Cpp格式规则同样适用于C语言
Standard: Latest # 使用最新的C++标准,支持现代语法特性,如果只是c语言可与忽略
# 行宽限制配置
ColumnLimit: 120 # 每行最大字符数,超过后自动换行,适合嵌入式开发和代码审查
# ============================================================================= # 对齐和缩进配置 # =============================================================================
## 延续的行的缩进宽度
ContinuationIndentWidth: 4 # 续行缩进4个空格,保持与基础缩进一致
## 访问修饰符配置
AccessModifierOffset: -2 # public:/private: 相对于class缩进-2个空格
## 各种对齐规则
AlignAfterOpenBracket: Align # 函数参数与开括号对齐,提升参数列表可读性
AlignConsecutiveAssignments:
true # 连续赋值语句的等号垂直对齐,如:
# int x = 1;
# double y = 2.0;
AlignConsecutiveDeclarations: true # 连续变量声明的变量名垂直对齐,统一声明格式
AlignConsecutiveMacros: true # 连续宏定义的宏名垂直对齐,便于宏管理
AlignEscapedNewlines: Left # 多行宏定义的反斜杠左对齐
AlignOperands: true # 多行表达式中操作数对齐,提升复杂表达式可读性
AlignTrailingComments: true # 行尾注释垂直对齐,形成整齐的注释列
AlignArrayOfStructures: Right # 结构体数组对齐
AlignConsecutiveBitFields: true # 位域对齐声明
[[Clang11]]: AlignConsecutiveBitFields: true # Clang 11+: 对齐连续位域声明
[[Clang11]]: AlignAfterOperator # Clang 11+: 操作符后对齐
## 函数返回类型换行配置
AlwaysBreakAfterDefinitionReturnType:
None # 函数定义的返回类型与函数名保持同行
# None: int function() {}
# All: int # function() {}
# ============================================================================= # 参数和换行控制配置 # =============================================================================
## 参数换行限制
AllowAllArgumentsOnNextLine: false # 禁止函数调用参数全部换到下一行
AllowAllConstructorInitializersOnNextLine: false # 禁止构造函数初始化列表全部换行
AllowAllParametersOfDeclarationOnNextLine: false # 禁止函数声明参数全部换到下一行
## 单行代码控制 - 提升代码可读性
AllowShortBlocksOnASingleLine: Never # 禁止短代码块单行: if(x){ y=1; } → 必须换行
AllowShortCaseLabelsOnASingleLine: false # 禁止短case标签单行: case 1: break; → 必须换行
AllowShortFunctionsOnASingleLine: None # 禁止短函数单行: void f(){} → 必须换行
AllowShortIfStatementsOnASingleLine: Never # 禁止短if语句单行: if(x) y=1; → 必须换行
AllowShortLambdasOnASingleLine: None # 禁止短lambda单行,C++项目适用
AllowShortLoopsOnASingleLine: false # 禁止短循环单行: for(i=0;i<10;i++) {} → 必须换行
AllowShortEnumsOnASingleLine: false # 枚举不允许单行
InsertBraces: true
[[Clang11]]: AllowShortEnumsOnASingleLine: false # Clang 11+: 禁止短枚举单行 AlwaysBreakAfterReturnType: None # 函数声明返回类型与函数名保持同行 AlwaysBreakBeforeMultilineStrings: false # 多行字符串前不强制换行,保持紧凑 AlwaysBreakTemplateDeclarations: Yes # 模板声明强制换行,提升模板可读性
## 参数装箱控制 - 优化代码审查体验
BinPackArguments:
true # 禁止函数调用参数装箱,每个参数独占一行
# function(arg1, arg2, arg3) →
# function( # arg1, # arg2, # arg3 # )
BinPackParameters: false # 禁止函数声明参数装箱,便于参数管理和代码审查
# ============================================================================= # 大括号和运算符配置 # =============================================================================
BreakBeforeBraces:
Allman # 大括号风格: Allman (独占一行)
# void function() # { # if (condition) # { # // code # } # }
BreakBeforeBinaryOperators: None # 二元运算符换行: 运算符放在行末而非行首
BreakBeforeTernaryOperators: false # 三元运算符?: 和 : 放在行末
BreakConstructorInitializers: AfterColon # 构造函数初始化列表在冒号后换行
BreakInheritanceList: AfterColon # 继承列表在冒号后换行
BreakStringLiterals: true # 允许长字符串字面量自动换行
# ============================================================================= # C++特性和命名空间配置 # =============================================================================
CompactNamespaces: true # 压缩嵌套命名空间声明
Cpp11BracedListStyle: true # 使用C++11大括号初始化列表风格
DeriveLineEnding: false # 不自动检测行尾符,使用配置的UseCRLF设置
DerivePointerAlignment: false # 不自动检测指针对齐,使用配置的PointerAlignment
FixNamespaceComments: true # 自动修复命名空间结束注释
IncludeBlocks: Merge
# ============================================================================= # 缩进配置 # =============================================================================
IndentCaseLabels: true # case标签相对于switch缩进
IndentPPDirectives: None # 预处理指令不缩进 (#include, [[define等]])
IndentWidth: 4 # 基础缩进宽度: 4个空格
IndentWrappedFunctionNames: true # 换行的函数名进行缩进
[[Clang11]]: IndentCaseBlocks: true # Clang 11+: case块缩进
[[Clang11]]: IndentExternBlock: true # Clang 11+: extern "C" 块缩进
# ============================================================================= # 换行惩罚权重配置 - 调优自动换行算法 # =============================================================================
# 数值越小,越倾向于在该位置换行;数值越大,越避免在该位置换行
PenaltyBreakBeforeFirstParameter: 5 # 函数定义第一参数前换行惩罚(较低,容易换行)
PenaltyBreakBeforeFirstCallParameter: 5 # 函数调用第一参数前换行惩罚(较低,容易换行)
PenaltyBreakAssignment: 10 # 赋值运算符处换行惩罚(中等,适度换行)
PenaltyExcessCharacter: 100 # 每个超出ColumnLimit的字符惩罚(高,强制换行)
# ============================================================================= # 空行和命名空间配置 # =============================================================================
KeepEmptyLinesAtTheStartOfBlocks: false # 代码块开始处不保留空行,保持紧凑
MaxEmptyLinesToKeep: 1 # 最多保留1个连续空行,避免过多空白
NamespaceIndentation: All # 命名空间内所有内容都缩进
PenaltyReturnTypeOnItsOwnLine: 0 # 返回类型独占一行无惩罚(允许)
PointerAlignment: Right # 指针星号靠右对齐: char *ptr (而非 char* ptr)
ReflowComments: true # 自动重新格式化注释以适应ColumnLimit
SortIncludes: true # 自动排序#include语句
# ============================================================================= # 包含文件排序优先级配置 # =============================================================================
# Priority值越小,排序越靠前;负数优先级最高
IncludeCategories:
- Regex: '"*PlatformIO.h"' # PlatformIO框架头文件 (最高优先级)
Priority: -5
- Regex: '"*TextIOTypes.h"' # 文本IO类型头文件
Priority: -4
- Regex: "<[Ww]indows.h>" # Windows系统头文件
Priority: -3
- Regex: '<*\/.h>' # 其他系统/库头文件 <xxx/yyy.h>
Priority: -2
- Regex: '"*\/.h"' # 项目本地头文件 "xxx/yyy.h"
Priority: 1
SortUsingDeclarations: true # 自动排序using声明
# ============================================================================= # 空格配置 - 精确控制各种位置的空格 # =============================================================================
## 类型转换和逻辑运算符
SpaceAfterCStyleCast: true # C风格类型转换后加空格: (int) x
SpaceAfterLogicalNot: false # 逻辑非运算符后不加空格: !condition
SpaceAfterTemplateKeyword: true # template关键字后加空格
## 赋值和初始化
SpaceBeforeAssignmentOperators: true # 赋值运算符前加空格: x = y
SpaceBeforeCpp11BracedList: true # C++11大括号初始化前加空格: vector<int> {1,2,3}
SpaceBeforeCtorInitializerColon: false # 构造函数初始化冒号前不加空格
SpaceBeforeInheritanceColon: false # 继承冒号前不加空格
## 括号和控制结构
SpaceBeforeParens: ControlStatements # 仅在控制语句圆括号前加空格: if (x) 但 func(x)
SpaceBeforeRangeBasedForLoopColon: false # 范围for循环冒号前不加空格
SpaceBeforeSquareBrackets: false # 方括号前不加空格: array[index]
## 括号内空格控制
SpaceInEmptyBlock: false # 空代码块内不加空格: {}
SpaceInEmptyParentheses: false # 空圆括号内不加空格: ()
SpacesInAngles: false # 模板尖括号内不加空格: <int>
SpacesInConditionalStatement: false # 条件语句圆括号内不加空格: if(condition)
SpacesInContainerLiterals: false # 容器字面量内不加空格: {1,2,3}
SpacesInCStyleCastParentheses: false # C风格转换圆括号内不加空格: (int)
SpacesInParentheses: false # 圆括号内不加空格: function(arg)
SpacesInSquareBrackets: false # 方括号内不加空格: array[index]
## 注释空格控制
SpacesBeforeTrailingComments: 2 # 行尾注释前2个空格: code; // comment
# ============================================================================= # Tab和行尾符配置 # =============================================================================
TabWidth: 4 # Tab等效宽度: 4个空格
UseCRLF: false # 使用Unix行尾符 (LF),适合跨平台开发
UseTab: Never # 永不使用Tab字符,统一使用空格缩进
# ============================================================================= # 配置说明:
# 本配置针对嵌入式C/C++项目优化,特点:
# - 可读性优先: Allman大括号风格,参数分行显示
# - 一致性: 自动对齐声明、赋值、注释
# - 适度限制: 120列宽度,适合代码审查
# - 严格规范: 统一的空格、缩进、换行规则
# =============================================================================
|