clang-format 配置

核心配置要求

  1. 行宽限制:ColumnLimit: 120,每行最多120字符,半个屏幕可显示完整
  2. 大括号风格:Allman风格,大括号独占一行,提升阅读体验
  3. 头文件排序:自动对Include的头文件排序
  4. 缩进规范:永不使用Tab字符,统一使用4个空格缩进

基础配置

1
2
3
Language: Cpp
Standard: Latest
ColumnLimit: 120

对齐规则

配置项 说明
AlignAfterOpenBracket Align 函数参数与开括号对齐
AlignConsecutiveAssignments true 连续赋值语句等号垂直对齐
AlignConsecutiveDeclarations true 连续变量声明变量名垂直对齐
AlignConsecutiveMacros true 连续宏定义垂直对齐
AlignEscapedNewlines Left 多行宏反斜杠左对齐
AlignOperands true 多行表达式操作数对齐
AlignTrailingComments true 行尾注释垂直对齐
AlignArrayOfStructures Right 结构体数组右对齐
AlignConsecutiveBitFields true 位域对齐声明

单行限制

1
2
3
4
5
6
7
8
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: None
AllowShortLoopsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
InsertBraces: true

换行配置

1
2
3
4
5
6
BreakBeforeBraces: Allman
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: true

参数装箱

1
2
3
4
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
BinPackArguments: false
BinPackParameters: false

缩进配置

1
2
3
4
5
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: true
NamespaceIndentation: All

空格配置

1
2
3
4
5
6
7
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpacesBeforeTrailingComments: 2

头文件排序优先级

1
2
3
4
5
6
7
8
9
10
11
12
13
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
SortIncludes: true
SortUsingDeclarations: true

Tab和行尾符

1
2
3
TabWidth: 4
UseCRLF: false
UseTab: Never

适用场景

本配置针对嵌入式C/C++项目优化:

  • 可读性优先:Allman大括号风格,参数分行显示
  • 一致性:自动对齐声明、赋值、注释
  • 适度限制:120列宽度,适合代码审查
  • 严格规范:统一的空格、缩进、换行规则