这份配置以 Google 风格为基础,覆盖缩进、对齐、括号、换行、包含文件排序及若干其他语言选项。配置文件是 YAML,应保存为项目中的 .clang-format;原稿的 bash 代码标签不能代表它的文件格式。本文按本机 clang-format 21.1.2 验证,并参照 21.1.2 选项说明。
先确认版本,再采用配置
跳转到“先确认版本,再采用配置”原稿的 147 个顶层键在该版本中全部被接受,不能把它们一概判断为无效。下面保留原有配置值,修正几处注释;没有靠删除不认识的规则来获得通过。21.1.2 的规范化输出会把旧名称或旧形式转换,例如:
| 原写法 | 21.1.2 规范化形式或实际含义 |
|---|---|
AlwaysBreakAfterReturnType | 输出为 BreakAfterReturnType |
AlwaysBreakTemplateDeclarations | 输出为 BreakTemplateDeclarations |
KeepEmptyLinesAtEOF / KeepEmptyLinesAtTheStartOfBlocks | 合入 KeepEmptyLines.AtEndOfFile / AtStartOfBlock |
BinPackParameters: true | 输出为 BinPack |
ReflowComments: true | 输出为 Always |
SortIncludes: CaseSensitive | 输出为 Enabled: true、IgnoreCase: false |
这些是本次工具输出确认的兼容行为,不是所有旧版本或未来版本的通用承诺。升级工具时重新解析配置并检查差异;BasedOnStyle 是默认值来源,--dump-config 展开继承和默认值后,不能再靠逐行相等判断配置是否改变。
容易误读的组合
跳转到“容易误读的组合”BreakBeforeBraces: Custom才让本配置的BraceWrapping细项决定对应的大括号换行。SpaceBeforeParens: Never不会采用SpaceBeforeParensOptions.AfterControlStatements: true来生成if (...);本例仍是if(...)。要启用这些细项,选择Custom。SpacesInParens: Never时,不按下面的SpacesInParensOptions逐项定制。DerivePointerAlignment: true先参考源文件;PointerAlignment: Left是后备值。ColumnLimit: 200是排版目标,不能保证字符串、注释或其他不可拆内容永远不超宽。Standard: Auto影响格式化解析,不会替构建系统加-std=c++17。
原配置还保留 Java、JavaScript、Objective-C、JSON 和 Verilog 选项;它们并不因此全部作用于当前 C++ 文件。特别是 BreakArrays 针对 JSON 数组,SpacesInContainerLiterals 也不是 C++ 初始化列表的通用开关。
完整配置
跳转到“完整配置”下面各值与原配置一致;注释经过修订。对项目应用前,应先在少量代表文件上检查结果。
---# 基于 Google 风格的代码格式化配置,并进行了一些自定义调整Language: Cpp # 指定语言为 C++BasedOnStyle: Google # 基于 Google 风格
# 缩进和对齐相关AccessModifierOffset: -4 # 访问修饰符(如 public, private)的缩进偏移量AlignAfterOpenBracket: Align # 在左括号后对齐内容AlignArrayOfStructures: None # 不对数组的结构体进行特殊对齐AlignConsecutiveAssignments: # 连续赋值语句对齐 Enabled: true # 启用对齐 AcrossEmptyLines: false # 不跨空行对齐 AcrossComments: false # 不跨注释对齐 AlignCompound: false # 不对复合赋值操作符对齐 AlignFunctionPointers: false # 不对函数指针对齐 PadOperators: true # 对较短赋值操作符补空格,以便和较长操作符对齐AlignConsecutiveBitFields: # 连续位字段对齐,未启用 Enabled: falseAlignConsecutiveDeclarations: # 连续声明对齐 Enabled: true # 启用对齐 AcrossEmptyLines: false AcrossComments: false AlignCompound: false AlignFunctionPointers: false PadOperators: falseAlignConsecutiveMacros: # 宏对齐 Enabled: true # 启用对齐 AcrossEmptyLines: false AcrossComments: false AlignCompound: false AlignFunctionPointers: false PadOperators: falseAlignConsecutiveShortCaseStatements: # 短的 case 语句对齐,未启用 Enabled: falseAlignEscapedNewlines: Left # 转义换行符的对齐方式为左对齐AlignOperands: Align # 操作数对齐AlignTrailingComments: # 尾部注释对齐 Kind: Always # 总是对齐 OverEmptyLines: 0 # 不跨空行对齐
# 简短代码块和函数的格式化AllowAllArgumentsOnNextLine: true # 若参数列表需要换行,允许全部参数放到下一行AllowAllParametersOfDeclarationOnNextLine: true # 若形参列表需要换行,允许全部形参放到下一行AllowBreakBeforeNoexceptSpecifier: Never # 不在 noexcept 前换行AllowShortBlocksOnASingleLine: Never # 不允许简短的代码块写在一行AllowShortCaseLabelsOnASingleLine: false # 不允许简短的 case 标签写在一行AllowShortCompoundRequirementOnASingleLine: true # 允许简短的复合要求写在一行AllowShortEnumsOnASingleLine: true # 允许简短的枚举写在一行AllowShortFunctionsOnASingleLine: None # 不允许简短的函数写在一行AllowShortIfStatementsOnASingleLine: Never # 不允许简短的 if 语句写在一行AllowShortLambdasOnASingleLine: All # 允许简短的 lambda 表达式写在一行AllowShortLoopsOnASingleLine: true # 允许简短的循环写在一行
# 大括号和代码块的格式化AlwaysBreakAfterDefinitionReturnType: None # 不在定义的返回类型后强制换行AlwaysBreakAfterReturnType: None # 不在返回类型后强制换行AlwaysBreakBeforeMultilineStrings: true # 在适用且能改善排版的多行字符串前考虑换行AlwaysBreakTemplateDeclarations: Yes # 在模板声明后强制换行AttributeMacros: # 属性宏 - __capabilityBinPackArguments: true # 列表换行时,允许一行容纳多个实参BinPackParameters: true # 列表换行时,允许一行容纳多个形参BitFieldColonSpacing: Both # 位字段冒号两侧都添加空格BraceWrapping: # 大括号换行规则 AfterCaseLabel: false # case 标签后不换行 AfterClass: true # 类定义后换行 AfterControlStatement: Always # 控制语句后总是换行 AfterEnum: false # 枚举定义后不换行 AfterExternBlock: false # extern 块后不换行 AfterFunction: true # 函数定义后换行 AfterNamespace: false # 命名空间定义后不换行 AfterObjCDeclaration: false # Objective-C 声明后不换行 AfterStruct: false # 结构体定义后不换行 AfterUnion: false # 联合体定义后不换行 BeforeCatch: false # catch 前不换行 BeforeElse: false # else 前不换行 BeforeLambdaBody: false # lambda 体前不换行 BeforeWhile: false # while 前不换行 IndentBraces: false # 不缩进大括号本身 SplitEmptyFunction: true # 空函数体分两行 SplitEmptyRecord: true # 空记录分两行 SplitEmptyNamespace: true # 空命名空间分两行BreakAdjacentStringLiterals: true # 分割相邻的字符串字面量BreakAfterAttributes: Leave # 属性后换行规则:保留原样BreakAfterJavaFieldAnnotations: false # Java 字段注解后不换行BreakArrays: true # 该选项针对 JSON 数组;不是 C++ 数组声明规则BreakBeforeBinaryOperators: None # 二元运算符前不换行BreakBeforeConceptDeclarations: Always # 模板声明与后续 concept 声明之间换行BreakBeforeBraces: Custom # 自定义大括号换行规则BreakBeforeInlineASMColon: OnlyMultiline # 内联汇编冒号前换行规则:仅在多行时BreakBeforeTernaryOperators: true # 三元运算符前换行BreakConstructorInitializers: BeforeColon # 初始化列表换行时,将冒号放在新行BreakInheritanceList: BeforeColon # 继承列表换行时,将冒号放在新行BreakStringLiterals: true # 字符串字面量换行
# 代码宽度和换行ColumnLimit: 200 # 列宽目标;无法拆分的内容等情况仍可超出ConstructorInitializerIndentWidth: 4 # 构造函数初始化列表的缩进宽度ContinuationIndentWidth: 4 # 续行缩进宽度Cpp11BracedListStyle: true # C++11 初始化列表风格DerivePointerAlignment: true # 自动推导指针对齐方式DisableFormat: false # 不禁用格式化EmptyLineAfterAccessModifier: Never # 不在访问修饰符后添加空行EmptyLineBeforeAccessModifier: LogicalBlock # 依逻辑块规则处理访问修饰符前的空行ExperimentalAutoDetectBinPacking: false # 不实验性地从源代码推导参数列表的 bin-packing 风格FixNamespaceComments: true # 修复命名空间注释ForEachMacros: # foreach 宏 - foreach - Q_FOREACH - BOOST_FOREACHIfMacros: # if 宏 - KJ_IF_MAYBEIncludeBlocks: Regroup # 重新分组 include 块IncludeCategories: # include 分类规则 - Regex: '^<ext/.*\.h>' # 匹配 <ext/*.h> Priority: 2 # 优先级 2 SortPriority: 0 # 排序优先级 0 CaseSensitive: false # 不区分大小写 - Regex: '^<.*\.h>' # 匹配 <*.h> Priority: 1 # 优先级 1 SortPriority: 0 # 排序优先级 0 CaseSensitive: false # 不区分大小写 - Regex: '^<.*' # 匹配 <* Priority: 2 # 优先级 2 SortPriority: 0 # 排序优先级 0 CaseSensitive: false # 不区分大小写 - Regex: '.*' # 匹配所有 Priority: 3 # 优先级 3 SortPriority: 0 # 排序优先级 0 CaseSensitive: false # 不区分大小写IncludeIsMainRegex: '([-_](test|unittest))?$' # 匹配主文件的正则表达式IncludeIsMainSourceRegex: '' # 匹配主源文件的正则表达式为空IndentAccessModifiers: false # 不缩进访问修饰符IndentCaseBlocks: false # 不缩进 case 块IndentCaseLabels: true # 缩进 case 标签IndentExternBlock: AfterExternBlock # extern 块缩进规则IndentGotoLabels: true # 缩进 goto 标签IndentPPDirectives: BeforeHash # 预处理指令缩进规则:在井号前缩进IndentRequiresClause: true # 缩进 requires 子句IndentWidth: 4 # 缩进宽度IndentWrappedFunctionNames: false # 不缩进包装的函数名InsertBraces: false # 不插入大括号InsertNewlineAtEOF: false # 不在文件末尾插入换行符InsertTrailingCommas: None # 不插入尾随逗号IntegerLiteralSeparator: # 整数字面量分隔符 Binary: 0 BinaryMinDigits: 0 Decimal: 0 DecimalMinDigits: 0 Hex: 0 HexMinDigits: 0JavaScriptQuotes: Leave # 保留 JavaScript 引号JavaScriptWrapImports: true # 包装 JavaScript 导入KeepEmptyLinesAtTheStartOfBlocks: false # 不保留块开头的空行KeepEmptyLinesAtEOF: false # 不保留文件末尾的空行LambdaBodyIndentation: Signature # lambda 体缩进规则LineEnding: DeriveLF # 从文件推导换行风格;无法推导时使用 LFMacroBlockBegin: '' # 宏块开始为空MacroBlockEnd: '' # 宏块结束为空MaxEmptyLinesToKeep: 1 # 保留的最大空行数NamespaceIndentation: None # 命名空间不缩进ObjCBinPackProtocolList: Never # Objective-C 协议列表不打包ObjCBlockIndentWidth: 4 # Objective-C 块缩进宽度ObjCBreakBeforeNestedBlockParam: true # Objective-C 嵌套块参数前换行ObjCSpaceAfterProperty: false # Objective-C 属性后不加空格ObjCSpaceBeforeProtocolList: true # Objective-C 协议列表前加空格PackConstructorInitializers: NextLine # 当前行放不下时,优先将初始化器集中在下一行PenaltyBreakAssignment: 2 # 分割赋值语句的惩罚值PenaltyBreakBeforeFirstCallParameter: 1 # 分割第一个调用参数的惩罚值PenaltyBreakComment: 300 # 分割注释的惩罚值PenaltyBreakFirstLessLess: 120 # 分割第一个 << 的惩罚值PenaltyBreakOpenParenthesis: 0 # 分割左括号的惩罚值PenaltyBreakScopeResolution: 500 # 分割作用域解析的惩罚值PenaltyBreakString: 1000 # 分割字符串的惩罚值PenaltyBreakTemplateDeclaration: 10 # 分割模板声明的惩罚值PenaltyExcessCharacter: 1000000 # 超出字符的惩罚值PenaltyIndentedWhitespace: 0 # 缩进空格的惩罚值PenaltyReturnTypeOnItsOwnLine: 200 # 返回类型单独一行的惩罚值PointerAlignment: Left # 左对齐后备值;DerivePointerAlignment=true 时先从文件推导PPIndentWidth: -1 # 预处理指令缩进宽度QualifierAlignment: Leave # 限定符对齐规则:保留原样RawStringFormats: # 原始字符串格式 - Language: Cpp # 语言为 C++ Delimiters: # 分隔符 - cc - CC - cpp - Cpp - CPP - 'c++' - 'C++' CanonicalDelimiter: '' # 标准分隔符为空 BasedOnStyle: google # 基于 Google 风格 - Language: TextProto # 语言为 TextProto Delimiters: # 分隔符 - pb - PB - proto - PROTO EnclosingFunctions: # 包裹函数 - EqualsProto - EquivToProto - PARSE_PARTIAL_TEXT_PROTO - PARSE_TEST_PROTO - PARSE_TEXT_PROTO - ParseTextOrDie - ParseTextProtoOrDie - ParseTestProto - ParsePartialTestProto CanonicalDelimiter: pb # 标准分隔符为 pb BasedOnStyle: google # 基于 Google 风格ReferenceAlignment: Pointer # 引用对齐方式与指针相同ReflowComments: true # 重新排版注释RemoveBracesLLVM: false # 不移除 LLVM 风格的大括号RemoveParentheses: Leave # 不移除括号RemoveSemicolon: false # 不移除分号RequiresClausePosition: OwnLine # requires 子句位置:单独一行RequiresExpressionIndentation: OuterScope # requires 表达式缩进规则SeparateDefinitionBlocks: Leave # 分离定义块规则:保留原样ShortNamespaceLines: 1 # 简短命名空间的行数SkipMacroDefinitionBody: false # 不跳过宏定义体SortIncludes: CaseSensitive # 区分大小写排序 includeSortJavaStaticImport: Before # Java 静态导入排序规则SortUsingDeclarations: LexicographicNumeric # using 声明排序规则SpaceAfterCStyleCast: false # C 风格强制转换后不加空格SpaceAfterLogicalNot: false # 逻辑非操作符后不加空格SpaceAfterTemplateKeyword: true # 模板关键字后加空格SpaceAroundPointerQualifiers: Default # 指针限定符周围空格规则:默认SpaceBeforeAssignmentOperators: true # 赋值操作符前加空格SpaceBeforeCaseColon: false # case 冒号前不加空格SpaceBeforeCpp11BracedList: false # C++11 初始化列表前不加空格SpaceBeforeCtorInitializerColon: true # 构造函数初始化列表前加空格SpaceBeforeInheritanceColon: true # 继承冒号前加空格SpaceBeforeJsonColon: false # JSON 冒号前不加空格SpaceBeforeParens: Never # 左括号前不加空格SpaceBeforeParensOptions: # 仅 SpaceBeforeParens=Custom 时按这些细项定制 AfterControlStatements: true # 控制语句后加空格 AfterForeachMacros: true # foreach 宏后加空格 AfterFunctionDefinitionName: false # 函数定义名后不加空格 AfterFunctionDeclarationName: false # 函数声明名后不加空格 AfterIfMacros: true # if 宏后加空格 AfterOverloadedOperator: false # 重载操作符后不加空格 AfterPlacementOperator: true # 放置操作符后加空格 AfterRequiresInClause: false # requires 子句后不加空格 AfterRequiresInExpression: false # requires 表达式后不加空格 BeforeNonEmptyParentheses: false # 非空括号前不加空格SpaceBeforeRangeBasedForLoopColon: true # 基于范围的 for 循环冒号前加空格SpaceBeforeSquareBrackets: false # 方括号前不加空格SpaceInEmptyBlock: false # 空代码块内不加空格SpacesBeforeTrailingComments: 2 # 尾部注释前的空格数SpacesInAngles: Never # 尖括号内不加空格SpacesInContainerLiterals: true # 适用于 Objective-C/JavaScript 等容器字面量SpacesInLineCommentPrefix: # 行注释前缀空格 Minimum: 1 # 最小空格数 Maximum: -1 # 最大空格数(无限制)SpacesInParens: Never # 括号内不加空格SpacesInParensOptions: # 仅 SpacesInParens=Custom 时按这些细项定制 InCStyleCasts: false # C 风格强制转换内不加空格 InConditionalStatements: false # 条件语句内不加空格 InEmptyParentheses: false # 空括号内不加空格 Other: false # 其他情况不加空格SpacesInSquareBrackets: false # 方括号内不加空格Standard: Auto # 推导格式化所用语法风格;不会设置编译器语言标准StatementAttributeLikeMacros: # 类似属性的宏 - Q_EMITStatementMacros: # 语句宏 - Q_UNUSED - QT_REQUIRE_VERSIONTabWidth: 8 # 制表符宽度UseTab: Never # 不使用制表符VerilogBreakBetweenInstancePorts: true # Verilog 实例端口之间换行WhitespaceSensitiveMacros: # 对空格敏感的宏 - BOOST_PP_STRINGIZE - CF_SWIFT_NAME - NS_SWIFT_NAME - PP_STRINGIZE - STRINGIZE...在项目中使用
跳转到“在项目中使用”将上面的 YAML 保存为 .clang-format,在终端运行:
clang-format --versionclang-format --style=file --dump-configclang-format --style=file example.cpp > example.formatted.cppclang-format --style=file --dry-run --Werror example.formatted.cpp--style=file 按输入文件所在目录向上查找配置;从标准输入格式化时,可用 --assume-filename=example.cpp 提供文件名语境。需要直接更新原文件时使用 -i,先查看项目差异。命令行说明。
同一段 C++ 的实际结果
跳转到“同一段 C++ 的实际结果”输入文件:
#include <cassert>
class Counter{public:int add(int a,int b){if(a>0){return a+b;}return b;}};int main(){Counter counter;assert(counter.add(1,2)==3);}使用本配置的输出:
#include <cassert>
class Counter{public: int add(int a, int b) { if(a > 0) { return a + b; } return b; }};int main(){ Counter counter; assert(counter.add(1, 2) == 3);}本机还把输出再次格式化,结果逐字一致;仅将 SpaceBeforeParens 改为 Custom 的对照配置会得到 if (a > 0)。这说明主选项和细项需要一起理解。格式化器不进行完整的 C++ 编译或语义验证,格式正确也不能替代项目构建。
来源:CSDN 原文,首次发布于 2025-04-16。