在 clangd 中使用 clang-format 时,要控制大括号的换行风格,你需要配置.clang-format文件。以下是常用的大括号换行配置选项:
1. 创建或修改.clang-format文件
在你的项目根目录或用户目录创建此文件:
# 基础风格(可选的预设)BasedOnStyle:LLVM# 或 Google, Chromium, Mozilla, WebKit 等# 函数定义的大括号换行BreakBeforeBraces:Custom# 设置为Custom以便自定义控制# 详细的括号换行配置BraceWrapping:AfterClass:true# 类定义后换行AfterControlStatement:true# 控制语句后换行AfterEnum:true# 枚举定义后换行AfterFunction:true# 函数定义后换行AfterNamespace:true# 命名空间后换行AfterObjCDeclaration:trueAfterStruct:true# 结构体定义后换行AfterUnion:true# 联合定义后换行AfterExternBlock:trueBeforeCatch:trueBeforeElse:trueBeforeLambdaBody:falseBeforeWhile:falseIndentBraces:falseSplitEmptyFunction:trueSplitEmptyRecord:trueSplitEmptyNamespace:true2. 推荐的配置(大括号全部换行)
BasedOnStyle:LLVMBreakBeforeBraces:Allman# 或使用自定义设置:BraceWrapping:AfterClass:trueAfterControlStatement:AlwaysAfterEnum:trueAfterFunction:trueAfterNamespace:trueAfterStruct:trueAfterUnion:trueAfterExternBlock:true3. 针对不同情况的配置示例
示例 1:Allman 风格(大括号总是换行)
BasedOnStyle:LLVMBreakBeforeBraces:Allman示例 2:函数大括号换行,其他不换
BasedOnStyle:LLVMBreakBeforeBraces:CustomBraceWrapping:AfterFunction:trueAfterClass:falseAfterControlStatement:Never4. 完整的配置示例
Language:CppBasedOnStyle:LLVMAccessModifierOffset:-2AlignAfterOpenBracket:AlignAlignEscapedNewlines:LeftAlignOperands:trueAllowShortBlocksOnASingleLine:NeverAllowShortCaseLabelsOnASingleLine:falseAllowShortFunctionsOnASingleLine:NoneAllowShortIfStatementsOnASingleLine:NeverAllowShortLoopsOnASingleLine:falseAlwaysBreakAfterReturnType:NoneAlwaysBreakBeforeMultilineStrings:trueBreakBeforeBinaryOperators:NoneBreakBeforeBraces:CustomBraceWrapping:AfterClass:trueAfterControlStatement:AlwaysAfterEnum:trueAfterFunction:trueAfterNamespace:trueAfterStruct:trueAfterUnion:trueAfterExternBlock:trueColumnLimit:120IndentWidth:4UseTab:NeverTabWidth:4PointerAlignment:LeftSpaceAfterCStyleCast:falseIndentCaseLabels:true5. 验证配置
- 安装 clang-format:
# Ubuntu/Debiansudoapt-getinstallclang-format# macOSbrewinstallclang-format# 或通过 LLVM- 测试格式化效果:
clang-format --style=file -i yourfile.cpp6. 在 VSCode 中配置
在.vscode/settings.json中添加:
{"clangd.fallbackFlags":["--query-driver=*"],"C_Cpp.formatting":"disabled","[cpp]":{"editor.formatOnSave":true}}注意事项:
.clang-format文件应该放在项目根目录- 可以在文件头部使用
#注释配置项的含义 - 可以使用
clang-format -style=file -dump-config查看当前配置 - BreakBeforeBraces 预设值有:Attach, Linux, Stroustrup, Allman, GNU, WebKit, Mozilla, Custom
选择适合你团队编码风格的配置即可。