在 Visual Studio Code 中配置 Clang-Format 格式化 (排版) 工具

发布时间:2026/9/14 11:44:50

在 Visual Studio Code 中配置 Clang-Format 格式化 (排版) 工具 在 Visual Studio Code 中配置 Clang-Format 格式化 {排版} 工具1. Install clang-format on Linux2. Create the .clang-format file3. Install the Clang-Format extension4. Configure ClangFormat options5. Code formatting6. 自定义 clang-format 代码格式规范ReferencesClang Formathttps://clang.llvm.org/docs/ClangFormat.htmlClang-Format Style Optionshttps://clang.llvm.org/docs/ClangFormatStyleOptions.htmlclang-formatis located inclang/tools/clang-formatand can be used to format C/C/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.1. Installclang-formaton LinuxInstallclang-formatby entering the following commandsyongqiangyongqiang:~$ sudo apt update yongqiangyongqiang:~$ sudo apt-cache search clang-format # This command will list all the available versions. yongqiangyongqiang:~$ sudo apt install clang-format -yDisplay the version of this programyongqiangyongqiang:~$ clang-format --version clang-format version 10.0.0-4ubuntu1 yongqiangyongqiang:~$ yongqiangyongqiang:~$ whereis clang-format clang-format: /usr/bin/clang-format /usr/share/man/man1/clang-format.1.gz yongqiangyongqiang:~$ yongqiangyongqiang:~$ which clang-format /usr/bin/clang-format yongqiangyongqiang:~$Ifclang-formatis in your system path, you shouldn’t need to do anything.Create a symbolic link for clang-format:sudo ln -s /usr/bin/clang-format-9.0 /usr/bin/clang-format sudo ln -s /usr/bin/clang-format-6.0 /usr/bin/clang-format2. Create the.clang-formatfileAn easy way to get a valid.clang-formatfile containing all configuration options of a certain predefined style is:clang-format -stylegoogle -dump-config .clang-format clang-format -stylellvm -dump-config .clang-formatyongqiangyongqiang:~/software$ clang-format -stylegoogle -dump-config .clang-format yongqiangyongqiang:~/software$ ll total 16 drwxr-xr-x 2 yongqiang yongqiang 4096 May 8 22:46 ./ drwxr-xr-x 13 yongqiang yongqiang 4096 May 7 10:10 ../ -rw-r--r-- 1 yongqiang yongqiang 4523 May 8 22:46 .clang-format yongqiangyongqiang:~/software$The style used for all options not specifically set in the configuration. Possible values:LLVM: A style complying with the LLVM coding standardsGoogle: A style complying with Google’s C style guideChromium: A style complying with Chromium’s style guideMozilla:A style complying with Mozilla’s style guideWebKit: A style complying with WebKit’s style guideMicrosoft: A style complying with Microsoft’s style guideGNU: A style complying with the GNU coding standards3. Install the Clang-Format extension4. Configure ClangFormat optionsFile - Preferences - Settings - Remote [*] - Clang-Format configurationAssume Filename:/home/yongqiang/software/.clang-formatWhen reading from stdin, clang-format assumes this filename to look for a style config file (with-stylefile) and to determine the language.Executable:/usr/bin/clang-formatclang-format executable pathFallback Style:Googleclang-format fallback style. (-fallback-stylevalue, value can be none, LLVM, Google, Chromium, Mozilla, WebKit)Style:fileclang-format style.(-stylevalue, value can be file, LLVM, Google, Chromium, Mozilla, WebKit or json configure)5. Code formattingThe C/C extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.Format Document With…Configure Default Formatter…Clang-FormatYou can format an entire file withFormat Document(ShiftAltF) or just the current selection withFormat Selection(CtrlK CtrlF) in right-click context menu. You can also configure auto-formatting with the following settings:editor.formatOnSave- to format when you save your file.editor.formatOnType- to format as you type (triggered on the;character).By default, the clang-format style is set to “file” which means it looks for a.clang-formatfile inside your workspace. If the.clang-formatfile is found, formatting is applied according to the settings specified in the file. If no.clang-formatfile is found in your workspace, formatting is applied based on a default style specified in theC_Cpp.clang_format_fallbackStylesetting instead.6. 自定义 clang-format 代码格式规范可以将生成的.clang-format文件提交到 Git 仓库。这样团队里的每一个人在按下“格式化代码”快捷键时代码风格都能保持绝对一致。clang-format -stylegoogle -dump-config .clang-format以 Google 的代码风格为蓝本生成一份完整的 clang-format 配置文件 (命名为.clang-format) 并保存到当前目录下。-stylegoogle: 指定基础的代码风格-dump-config: 导出/转储完整的配置参数 .clang-format: 重定向输出到文件yongqiangyongqiang:~/software$ clang-format -stylegoogle -dump-config .clang-format yongqiangyongqiang:~/software$ ll total 16 drwxr-xr-x 2 yongqiang yongqiang 4096 May 8 22:46 ./ drwxr-xr-x 13 yongqiang yongqiang 4096 May 7 10:10 ../ -rw-r--r-- 1 yongqiang yongqiang 4523 May 8 22:46 .clang-format yongqiangyongqiang:~/software$ yongqiangyongqiang:~/software$ cat ./.clang-format --- Language: Cpp # BasedOnStyle: Google AccessModifierOffset: -1 AlignAfterOpenBracket: Align AlignConsecutiveMacros: false AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: true AllowAllArgumentsOnNextLine: true AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: WithoutElse AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: Yes BinPackArguments: true BinPackParameters: true BraceWrapping: AfterCaseLabel: false AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Attach BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 80 CommentPragmas: ^ IWYU pragma: CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DeriveLineEnding: true DerivePointerAlignment: true DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Regroup IncludeCategories: - Regex: ^ext/.*\.h Priority: 2 SortPriority: 0 - Regex: ^.*\.h Priority: 1 SortPriority: 0 - Regex: ^.* Priority: 2 SortPriority: 0 - Regex: .* Priority: 3 SortPriority: 0 IncludeIsMainRegex: ([-_](test|unittest))?$ IncludeIsMainSourceRegex: IndentCaseLabels: true IndentGotoLabels: true IndentPPDirectives: None IndentWidth: 2 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: MacroBlockEnd: MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Never ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 1 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Left RawStringFormats: - Language: Cpp Delimiters: - cc - CC - cpp - Cpp - CPP - c - C CanonicalDelimiter: BasedOnStyle: google - Language: TextProto Delimiters: - pb - PB - proto - PROTO EnclosingFunctions: - EqualsProto - EquivToProto - PARSE_PARTIAL_TEXT_PROTO - PARSE_TEST_PROTO - PARSE_TEXT_PROTO - ParseTextOrDie - ParseTextProtoOrDie CanonicalDelimiter: BasedOnStyle: google ReflowComments: true SortIncludes: true SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyBlock: false SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 SpacesInAngles: false SpacesInConditionalStatement: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false SpaceBeforeSquareBrackets: false Standard: Auto StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 8 UseCRLF: false UseTab: Never ... yongqiangyongqiang:~/software$Yongqiang Cheng 自定义Google 风格可能 90% 符合你的习惯但有些细节你想改 (比如 Google 默认缩进 2 空格你想改成 4 空格)。生成这个文件后你可以直接打开它修改其中的某几行。ColumnLimit: 120 (单行代码最大长度限制)The column limit.允许单行代码最多包含 120 个字符。超过 120 个字符时clang-format 才会强制将代码拆分换行。IndentWidth: 4 (缩进宽度)The number of columns to use for indentation.每一次代码缩进都使用 4 个字符宽度。TabWidth: 4 (Tab 键宽度)The number of columns used for tab stops.定义一个制表符 (Tab 键) 在显示时应该占据几个字符的宽度。References[1] Yongqiang Cheng (程永强), https://yongqiang.blog.csdn.net/[2] Edit C in Visual Studio Code, https://code.visualstudio.com/docs/cpp/cpp-ide[3] Clang-Format Style Options, https://clang.llvm.org/docs/ClangFormatStyleOptions.html[4] Options, Text Editor, C/C, Formatting, https://learn.microsoft.com/en-us/visualstudio/ide/reference/options-text-editor-c-cpp-formatting[5] 在 Visual Studio Code 中配置 Clang-Format 格式化 (排版) 工具, https://mp.weixin.qq.com/s/b4Qv78TleWn400PINP_Xzw
延伸阅读

更多相关文章

2026/9/13 2:46:09

Claude Code:从代码补全到深度理解的AI编程代理实践指南

如果你是一名开发者,最近可能已经感受到了AI编程助手带来的效率革命。但当你面对一个全新的代码库,需要快速理解架构、修复bug或实现功能时,传统的代码补全工具往往显得力不从心。这正是Claude Code试图解决的核心痛点——它不仅仅是一个代码…

2026/9/14 20:55:30

Vue3双向绑定进阶:defineModel多变量与修饰符实战

1. Vue3双向绑定组件的核心价值与挑战双向绑定一直是Vue框架最标志性的特性之一。在Vue3中,随着Composition API的成熟和defineModel宏的引入,双向绑定的实现方式变得更加优雅和强大。但在实际开发中,我们经常会遇到需要处理多个绑定变量和自…

2026/9/14 20:55:30

2026届科研必备:AI学术平台核心能力评测与应用指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/14 20:55:30

OpenBB开源金融数据平台:架构解析与实战应用

1. OpenBB平台概述:金融数据的开源革命OpenBB正在重新定义金融数据分析的边界。这个完全开源的项目为分析师、量化交易员和AI开发者提供了一个统一的金融数据接入层。想象一下,你不再需要为每个数据源编写不同的API调用代码,不再需要处理五花…

2026/9/14 20:55:30

Excel高效数据处理与分析技巧全解析

1. Excel基础功能与核心价值解析Excel作为微软Office套件中的核心组件,已经发展成为数据处理和分析领域的标准工具。这款电子表格软件最初发布于1985年,经过三十多年的迭代进化,其功能已远远超出了简单的数据记录范畴。现代Excel集成了公式计…

2026/9/14 20:55:30

项目管理系统ROI计算中的五大收益高估陷阱

1. 项目管理系统ROI计算中的常见收益高估陷阱在评估项目管理系统的投资回报率时,很多企业会陷入"数字游戏"的误区。作为经历过数十个系统实施案例的从业者,我发现ROI计算中最容易被夸大的收益主要集中在以下五个方面:2. 最容易被高…

2026/9/14 2:17:50

拯救者Y7000黑屏故障排查与维修实战指南

1. 项目概述:一台黑屏的拯救者Y7000,到底卡在哪一步? 联想拯救者Y7000系列笔记本,从2018年第一代搭载i5-8300H开始,到后来的i7-9750H、i7-10750H、i5-11400H,再到2023年款的R7-7840HS,它始终是学…

2026/9/14 0:03:22

KCF目标跟踪算法与OTB工程实现:毕业设计实战解析

简介:这是一份基于KCF核相关滤波算法、融合尺度池与抗遮挡处理的目标检测跟踪MATLAB完整源码,主要面向计算机相关专业准备毕业设计、课程设计或期末大作业的学生,也适合需要项目实战练习的初学者。源码在OTB数据集上完成验证,能够…

2026/9/14 0:03:22

语音情感识别实战:Keras实现LSTM、CNN、SVM与MLP多模型对比

简介:面向语音情感识别入门与进阶开发者,这份基于Keras的项目源码完整实现了LSTM、CNN、SVM、MLP四种模型,兼容Python3.8与Keras/TensorFlow2环境。压缩包内含49个文件,大小约70.31MB,主体包括Python脚本、yaml/json配…

2026/9/14 11:59:31

USB Type-C PCB布局分区设计:电源、高速信号与PD协议全攻略

做硬件这行,Type-C接口算是典型的“看着简单,做起来全坑”的东西。光引脚就24个,高低速信号、电源、控制线全部塞在一个小小的连接器里,如果PCB布局不做规划,打样回来基本就是“插上没反应”、“高速掉线”、“静电一打…

2026/9/14 13:53:59

系统编程学习原型如何补齐稳定性边界

系统编程学习原型如何补齐稳定性边界预算有限时&#xff0c;我先优化明显多余的复制&#xff0c;而不是猜测性地换容器。用借用传递只读数据通常就能减少分配&#xff1a; fn parse(line: &str) -> Result<Item, Error> { /* ... */ }用基准确认热点确实在分配&am…

2026/9/14 11:22:57

雨花区哪家财务公司代理记账比较好?

在雨花区&#xff0c;企业处理财税事务常常面临诸多挑战&#xff0c;选择一家靠谱的财务公司至关重要。湖南巨勤财务管理咨询有限公司就是本地正规实体财税服务机构&#xff0c;深耕本地工商财税行业多年&#xff0c;熟悉当地工商局、税务局最新政策与申报流程。主营公司注册、…

还想了解更多?直接咨询顾问

免费诊断 + 免费方案 + 透明报价。

全国咨询热线400-8866-253
免费获取方案
咨询二维码