1665 字
8 分钟
快速上手clang-format规范代码
clang-format
食用方法
-
下载安装
clang-format工具 -
在vscode中安装
clang-format扩展 -
将下面配置保存在
.clang-format文件中,放置在项目的根目录下

-
在vscode设置中,找到
clang-format扩展设置,设置好刚刚写的文件路径,同时建议打开Format On Save选项

-
Ctrl+Shift+P,输入
Format Document,选择Clang-Format即可格式化当前文件
个人常用配置
Language: CppBasedOnStyle: LLVMUseTab: Never # 使用空格而不是制表符。IndentWidth: 4 # 缩进宽度为4个空格。TabWidth: 4 # Tab长度ColumnLimit: 80 # 单行的长度不超过80字符BreakBeforeBraces: Allman # 大括号风格BraceWrapping: AfterClass: true # 类定义的大括号另起一行 AfterControlStatement: true # 控制语句的大括号另起一行 AfterEnum: true # 枚举的大括号另起一行 AfterFunction: true # 函数的大括号另起一行 AfterNamespace: true # 命名空间的大括号另起一行 AfterObjCDeclaration: true # Objective-C 声明的大括号另起一行 AfterStruct: true # 结构体的大括号另起一行 AfterUnion: true # 联合体的大括号另起一行 AfterExternBlock: true # extern 块的大括号另起一行 BeforeCatch: true # catch 块的大括号另起一行 BeforeElse: true # else 块的大括号另起一行 IndentBraces: false # 大括号不缩进拓展内容
clang-format其他配置
Language: CppBasedOnStyle: Google
#访问声明符缩进AccessModifierOffset: -4
# 开括号后的对齐(包括小括号/大括号/尖括号), 建议使用Align# - Align: 对于开括号, 即在换行情况下, 换行的参数跟开括号对齐, 建议使用# - DontAlign: 不对于开括号, 即换行时使用配置的空格数# - AlwaysBreak: 永远换行, 即第一个参数都不允许粘连括号, 会强制换行, 换行后使用配置空格数对齐# - BlockIndent: 同AlwaysBreak, 多了一个操作: 如果参数不固定在同一行, 闭括号将在下一行AlignAfterOpenBracket: AlwaysBreak
# - 结构休数组统一初始化对齐, 建议不配置, 没过多必要, 详见clang-format doc# - None: 不做处理, 即保留开发者的代码# - Left: 左对齐# - Right: 右对齐AlignArrayOfStructures: None
# 连续赋值语句的对齐,即多个赋值语句连续出现时的对齐策略配置, 包含多个子配置项AlignConsecutiveAssignments: # 是否启用, 建议不启用 Enabled: false # 是否跨过空行, 即多个对齐语句中间有空行时, 是否跨过, 如果要开启连续赋值语句的配置, 建议为false AcrossEmptyLines: false # 是否跨过注释, 建议false AcrossComments: false # 是否跨过复合语句(包括空行及注释), 建议False AlignCompound: false AlignFunctionPointers: false
# 是否(右)对齐赋值操作的操作符, 建议true PadOperators: true
# 同AlignConsecutiveAssignments, 表示连续位定义语句出现时, 是否需要对齐:符号, 位变量定义用得少, 可以不开启AlignConsecutiveBitFields: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false AlignFunctionPointers: false PadOperators: falseAlignConsecutiveDeclarations: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCompound: false AlignFunctionPointers: false PadOperators: false
# 宏定义自动对齐AlignConsecutiveMacros: Enabled: true AcrossEmptyLines: false AcrossComments: false AlignCompound: false AlignFunctionPointers: false PadOperators: false
AlignConsecutiveShortCaseStatements: Enabled: false AcrossEmptyLines: false AcrossComments: false AlignCaseColons: false
# 续行符(\\)对齐:# - DontAlign: 不做操作# - Left: 尽可能向左对齐, 即最长一行代码为准# - Right: 跟开发都写的最远的\\对齐(即不会自动缩减你的空格), 建议使用这个AlignEscapedNewlines: RightAlignOperands: AlignAlignTrailingComments: Kind: Always OverEmptyLines: 0AllowAllArgumentsOnNextLine: trueAllowAllParametersOfDeclarationOnNextLine: trueAllowBreakBeforeNoexceptSpecifier: NeverAllowShortBlocksOnASingleLine: NeverAllowShortCaseLabelsOnASingleLine: falseAllowShortCompoundRequirementOnASingleLine: trueAllowShortEnumsOnASingleLine: trueAllowShortFunctionsOnASingleLine: AllAllowShortIfStatementsOnASingleLine: NeverAllowShortLambdasOnASingleLine: AllAllowShortLoopsOnASingleLine: falseAlwaysBreakAfterDefinitionReturnType: NoneAlwaysBreakAfterReturnType: NoneAlwaysBreakBeforeMultilineStrings: falseAlwaysBreakTemplateDeclarations: MultiLineAttributeMacros: - __capabilityBinPackArguments: trueBinPackParameters: true
# 位定义:前后是否增加空格, 可选:# - Both: 前后都添加# - Before: 只在前增加# - After: 只在后增加# - None: 不增加, 建议, 没有必要因为过多的space(s)影响代码紧凑BitFieldColonSpacing: None
# 大括号换行BraceWrapping: # 在case后的大括号是否换行 AfterCaseLabel: true # class后 AfterClass: true # 控制语句(if/for/while/switch/...)后是否换行 # - Never: 永远不, 即永远将语句体的大括号放置于控制语句同一行 # - MultiLine: 多行控制语句才进行换行 # - Always: 永远换行, 建议 AfterControlStatement: Always AfterEnum: true AfterExternBlock: false AfterFunction: true AfterNamespace: false AfterObjCDeclaration: false AfterStruct: true AfterUnion: true BeforeCatch: false BeforeElse: true BeforeLambdaBody: false BeforeWhile: true IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: trueBreakAdjacentStringLiterals: trueBreakAfterAttributes: LeaveBreakAfterJavaFieldAnnotations: falseBreakArrays: trueBreakBeforeBinaryOperators: NoneBreakBeforeConceptDeclarations: Always
# 大括号换行风格,Custom即可, 具体值可参考上方文档BreakBeforeBraces: CustomBreakBeforeInlineASMColon: OnlyMultilineBreakBeforeTernaryOperators: trueBreakConstructorInitializers: BeforeColonBreakInheritanceList: BeforeColonBreakStringLiterals: trueColumnLimit: 150CommentPragmas: '^ IWYU pragma:'CompactNamespaces: falseConstructorInitializerIndentWidth: 4ContinuationIndentWidth: 4
# C++11的统一初始化列表大括号风格, 建议trueCpp11BracedListStyle: trueDerivePointerAlignment: falseDisableFormat: falseEmptyLineAfterAccessModifier: NeverEmptyLineBeforeAccessModifier: LogicalBlockExperimentalAutoDetectBinPacking: falseFixNamespaceComments: trueForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACHIfMacros: - KJ_IF_MAYBE
# include代码块操作, 前提是SortIncludes开启:# - Preserve: 只对每个代码块排序# - Merge: 对所有代码块合并, 并在合并后排序# - Regroup: 对所有include块进行分析, 并重新分块, 不建议!IncludeBlocks: Preserve
IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 SortPriority: 0 CaseSensitive: false - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 SortPriority: 0 CaseSensitive: false - Regex: '.*' Priority: 1 SortPriority: 0 CaseSensitive: falseIncludeIsMainRegex: '(Test)?$'IncludeIsMainSourceRegex: ''IndentAccessModifiers: falseIndentCaseBlocks: falseIndentCaseLabels: falseIndentExternBlock: AfterExternBlockIndentGotoLabels: trueIndentPPDirectives: NoneIndentRequiresClause: trueIndentWidth: 4IndentWrappedFunctionNames: falseInsertBraces: falseInsertNewlineAtEOF: falseInsertTrailingCommas: NoneIntegerLiteralSeparator: Binary: 0 BinaryMinDigits: 0 Decimal: 0 DecimalMinDigits: 0 Hex: 0 HexMinDigits: 0JavaScriptQuotes: LeaveJavaScriptWrapImports: trueKeepEmptyLinesAtTheStartOfBlocks: trueKeepEmptyLinesAtEOF: falseLambdaBodyIndentation: SignatureLineEnding: DeriveLFMacroBlockBegin: ''MacroBlockEnd: ''MaxEmptyLinesToKeep: 1NamespaceIndentation: NoneObjCBinPackProtocolList: AutoObjCBlockIndentWidth: 2ObjCBreakBeforeNestedBlockParam: trueObjCSpaceAfterProperty: falseObjCSpaceBeforeProtocolList: true# 是否打包构造函数初始化列表, 建议Never, 可选:# - Never: 永远不做操作, 即一个参数一行# - BinPack: 两个参数一行# - CurrentLine: 所有参数放置于一行, 如果放不下, 就一个参数一行# - NextLine: 同CurrentLine有点像, 唯一不同就是如果放不行, 将剩余参数放置于下一行(即不自动一参一行)PackConstructorInitializers: NextLinePenaltyBreakAssignment: 2PenaltyBreakBeforeFirstCallParameter: 19PenaltyBreakComment: 300PenaltyBreakFirstLessLess: 120PenaltyBreakOpenParenthesis: 0PenaltyBreakScopeResolution: 500PenaltyBreakString: 1000PenaltyBreakTemplateDeclaration: 10PenaltyExcessCharacter: 1000000PenaltyIndentedWhitespace: 0PenaltyReturnTypeOnItsOwnLine: 60
# 指针对齐, 建议RightPointerAlignment: RightPPIndentWidth: -1QualifierAlignment: LeaveReferenceAlignment: Pointer
# 是否允许clang-format尝试重新粘合注释(true/false), 不建议使用ReflowComments: falseRemoveBracesLLVM: falseRemoveParentheses: LeaveRemoveSemicolon: false
# 模板中的require语句位置, 建议OwnLineRequiresClausePosition: OwnLineRequiresExpressionIndentation: OuterScope
# 分隔不同定义块, 建议Always, 可选:# - Leave - 不处理, 建议, 即由业务决定, 也可以使用Always# - Always - 永远进行分隔# - Never: 永远 不进行, 不建议SeparateDefinitionBlocks: LeaveShortNamespaceLines: 1SkipMacroDefinitionBody: falseSortIncludes: CaseSensitiveSortJavaStaticImport: BeforeSortUsingDeclarations: LexicographicNumericSpaceAfterCStyleCast: falseSpaceAfterLogicalNot: falseSpaceAfterTemplateKeyword: trueSpaceAroundPointerQualifiers: DefaultSpaceBeforeAssignmentOperators: trueSpaceBeforeCaseColon: falseSpaceBeforeCpp11BracedList: falseSpaceBeforeCtorInitializerColon: trueSpaceBeforeInheritanceColon: trueSpaceBeforeJsonColon: falseSpaceBeforeParens: ControlStatementsSpaceBeforeParensOptions: AfterControlStatements: true AfterForeachMacros: true AfterFunctionDefinitionName: false AfterFunctionDeclarationName: false AfterIfMacros: true AfterOverloadedOperator: false AfterPlacementOperator: true AfterRequiresInClause: false AfterRequiresInExpression: false BeforeNonEmptyParentheses: falseSpaceBeforeRangeBasedForLoopColon: trueSpaceBeforeSquareBrackets: falseSpaceInEmptyBlock: falseSpacesBeforeTrailingComments: 1SpacesInAngles: NeverSpacesInContainerLiterals: trueSpacesInLineCommentPrefix: Minimum: 1 Maximum: -1SpacesInParens: NeverSpacesInParensOptions: InCStyleCasts: false InConditionalStatements: false InEmptyParentheses: false Other: falseSpacesInSquareBrackets: falseStandard: LatestStatementAttributeLikeMacros: - Q_EMITStatementMacros: - Q_UNUSED - QT_REQUIRE_VERSIONTabWidth: 8UseTab: NeverVerilogBreakBetweenInstancePorts: trueWhitespaceSensitiveMacros: - BOOST_PP_STRINGIZE - CF_SWIFT_NAME - NS_SWIFT_NAME - PP_STRINGIZE - STRINGIZE 快速上手clang-format规范代码
https://github.com/adoreATRI/Note/tree/main/clang-format 部分信息可能已经过时



