发布时间:2026/7/22 2:27:36
在 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/7/20 21:27:57

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

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

2026/7/22 2:23:18

MySQL命令行操作与数据库管理实战指南

1. MySQL命令行基础:从零开始的数据库操作 MySQL作为最流行的开源关系型数据库之一,其命令行工具是每位开发者必须掌握的技能。无论是日常开发还是面试准备,熟练使用MySQL命令行都能让你事半功倍。让我们从最基础的连接操作开始。 1.1 连接…

2026/7/22 2:23:18

最新量化入门方法,先从概念规则和简单实现开始

入门量化时,最容易误判的是起点。很多人以为要先掌握完整技术,才能开始把交易规则写成 Python。其实更自然的路径,是先理解基本概念,再把手工规则说清,最后做一个简单实现。代码要回到规则本身概念帮助读者知道自己在表…

2026/7/22 2:23:18

Google 爬虫管理:抓取预算、404 与重定向

Google 爬虫管理:抓取预算、404 与重定向 一、抓取预算:Google 每天只爬你这么多页二、日志分析:上帝视角看 Google 怎么爬你三、404 页面:软 404 vs 硬 404硬 404软 404 四、自定义 404 页面与重定向重定向链自查三步走 五、爬虫…

2026/7/22 2:23:18

iPhone省电优化全攻略:延长续航的关键设置

1. iPhone省电优化的核心思路作为一名长期使用iPhone的深度用户,我发现在日常使用中电池续航是最影响体验的因素之一。很多人抱怨iPhone用久了会变卡顿、耗电快,其实这往往是因为忽略了一些系统自带的优化功能。经过多年实测,我发现通过合理设…

2026/7/22 2:18:18

真实攻防复盘:企业网站挂马入侵全过程拆解(从入侵到溯源清理)

📌 前言绝大多数新人只学靶场漏洞,从未见过真实入侵完整链路。真实黑客攻击不是单一漏洞点,而是漏洞利用→上传木马→权限维持→内网扩散→数据窃取的完整闭环。本文以一次真实企业官网挂马入侵事件做全流程复盘,带技术细节、阶段…

2026/7/20 6:33:00

Unity与Python本地通信:基于Flask的跨语言数据交换实战

1. 项目概述:为什么我们需要一个本地通信服务器?在游戏开发、数字孪生、仿真训练等众多领域,Unity作为强大的实时3D内容创作平台,其核心逻辑通常由C#驱动。然而,当我们需要进行复杂的数据分析、机器学习推理、科学计算…

2026/7/22 0:02:17

抓包代理链路下的 TLS 指纹变化分析 TLSFOWARD抓包工具

抓包代理链路下的 TLS 指纹变化分析:为什么调试环境会影响访问结果 摘要 在网页调试、接口联调、自动化巡检和授权采集排查中,抓包是常见手段。但很多开发者会遇到一个现象:正常访问页面时没有问题,一进入抓包或代理调试环境&…

2026/7/22 0:02:17

微信QQ聊天记录误删恢复与备份方案全指南

1. 聊天记录误删的常见场景与恢复思路作为一名长期关注数据安全的技术博主,我处理过上百起聊天记录误删的求助案例。手机误操作、系统升级失败、设备损坏是三大常见诱因。上周就遇到用户更新微信时断电,导致近两年的工作群聊记录全部消失的极端案例。不同…

2026/7/22 0:02:17

2026最新8款个人AI编程免费工具深度实测

作为一名全栈独立开发者,我最近半年一直在折腾副业项目,每个月在AI编程工具上的订阅费算下来其实也不算便宜。作为个人开发者,我们追求的就是用最少的成本获得最高效的开发体验。TRAE 基础版免费,字节跳动出品的国内首款 AI 原生 …

2026/7/21 20:02:44

3个高效策略:快速掌握Axure中文界面配置

3个高效策略:快速掌握Axure中文界面配置 【免费下载链接】axure-cn Chinese language file for Axure RP. Axure RP 简体中文语言包。支持 Axure 11、10、9。不定期更新。 项目地址: https://gitcode.com/gh_mirrors/ax/axure-cn 还在为Axure RP的英文界面感…