当前位置: 首页 > news >正文

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

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

  • 1. Install `clang-format` on Linux
  • 2. Create the `.clang-format` file
  • 3. Install the Clang-Format extension
  • 4. Configure ClangFormat options
  • 5. Code formatting
  • 6. 自定义 clang-format 代码格式规范
  • References

Clang Format
https://clang.llvm.org/docs/ClangFormat.html

Clang-Format Style Options
https://clang.llvm.org/docs/ClangFormatStyleOptions.html

clang-formatis located inclang/tools/clang-formatand can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

1. Installclang-formaton Linux

  1. Installclang-formatby entering the following commands
yongqiang@yongqiang:~$ sudo apt update yongqiang@yongqiang:~$ sudo apt-cache search clang-format # This command will list all the available versions. yongqiang@yongqiang:~$ sudo apt install clang-format -y
  1. Display the version of this program
yongqiang@yongqiang:~$ clang-format --version clang-format version 10.0.0-4ubuntu1 yongqiang@yongqiang:~$ yongqiang@yongqiang:~$ whereis clang-format clang-format: /usr/bin/clang-format /usr/share/man/man1/clang-format.1.gz yongqiang@yongqiang:~$ yongqiang@yongqiang:~$ which clang-format /usr/bin/clang-format yongqiang@yongqiang:~$

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-format

2. Create the.clang-formatfile

An easy way to get a valid.clang-formatfile containing all configuration options of a certain predefined style is:

clang-format -style=google -dump-config > .clang-format clang-format -style=llvm -dump-config > .clang-format
yongqiang@yongqiang:~/software$ clang-format -style=google -dump-config > .clang-format yongqiang@yongqiang:~/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 yongqiang@yongqiang:~/software$

The style used for all options not specifically set in the configuration. Possible values:

  • LLVM: A style complying with the LLVM coding standards
  • Google: A style complying with Google’s C++ style guide
  • Chromium: A style complying with Chromium’s style guide
  • Mozilla:A style complying with Mozilla’s style guide
  • WebKit: A style complying with WebKit’s style guide
  • Microsoft: A style complying with Microsoft’s style guide
  • GNU: A style complying with the GNU coding standards

3. Install the Clang-Format extension

4. Configure ClangFormat options

File -> Preferences -> Settings -> Remote [*] -> Clang-Format configuration

Assume Filename:/home/yongqiang/software/.clang-format

When reading from stdin, clang-format assumes this filename to look for a style config file (with-style=file) and to determine the language.

Executable:/usr/bin/clang-format

clang-format executable path

Fallback Style:Google

clang-format fallback style. (-fallback-style=value, value can be none, LLVM, Google, Chromium, Mozilla, WebKit)

Style:file

clang-format style.(-style=value, value can be file, LLVM, Google, Chromium, Mozilla, WebKit or json configure)

5. Code formatting

The C/C++ extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.

  1. Format Document With…

  1. Configure Default Formatter…

  1. Clang-Format

You can format an entire file withFormat Document(Shift+Alt+F) or just the current selection withFormat Selection(Ctrl+K Ctrl+F) 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 仓库。这样团队里的每一个人在按下“格式化代码”快捷键时,代码风格都能保持绝对一致。

  1. clang-format -style=google -dump-config > .clang-format

以 Google 的代码风格为蓝本,生成一份完整的 clang-format 配置文件 (命名为.clang-format) 并保存到当前目录下。

  • -style=google: 指定基础的代码风格
  • -dump-config: 导出/转储完整的配置参数
  • > .clang-format: 重定向输出到文件
yongqiang@yongqiang:~/software$ clang-format -style=google -dump-config > .clang-format yongqiang@yongqiang:~/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 yongqiang@yongqiang:~/software$ yongqiang@yongqiang:~/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 ... yongqiang@yongqiang:~/software$
  1. 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

http://www.jsqmd.com/news/1230570/

相关文章:

  • 2026年7月最新格拉苏蒂长沙万象城维修保养服务电话 - 亨得利钟表维修中心
  • ARK启动器终极优化指南:五步解决启动慢、卡顿与模组管理难题
  • 深入解析AM275x SoC互连架构:CBASS与QoS性能调优实战
  • 校服质量追溯合规指南:从国标到落地的全流程解析 - GrowthUME
  • 从Jupyter到生产:机器学习模型的可运维性设计与实践
  • 揭序加密技术:实现加密数据高效检索的创新方案
  • 终极桌面整理指南:如何用免费开源工具NoFences让Windows桌面焕然一新
  • LangChain生态工具选型指南:从开发到部署
  • AM64x/AM243x安全配置与调试寄存器实战解析
  • 河源浆板哪家好?2026 实地测评排名 - GrowthUME
  • Cursor新手黄金24小时训练计划(含官方未公开的CLI调试模式+3个内部Prompt诊断指令)
  • cad怎么转pdf哪个好?免费好用工具实测对比 - 软件小管家
  • OpenClaw太折腾?2026年这8款国产“AI龙虾“平替,小白也能5分钟上手
  • Python环境搭建指南:从安装到虚拟环境配置
  • print()大揭秘:如何用Python打印出多样字符
  • Zadig 官方 MCP Server 版本更新:接入更稳、调用更准、审计排障更清晰
  • 美度保养700售后维修保养服务中心权威公示(2026年7月最新) - 亨得利官方服务中心
  • 【2027最新】基于SpringBoot+Vue的图书管理系统管理系统源码+MyBatis+MySQL
  • Python入门:从零到一,掌握核心语法与编程思维
  • UG NX CAM编程实战:从零到一生成G代码的完整流程与核心技巧
  • SSH免密登录配置ssh-keygen -t rsa
  • C++协程异步网络框架详解与实战
  • Mongodb学习笔记,远程连接数据库
  • 2026年上半年,VC一半的钱砸进了AI:6500亿都流向了哪里
  • adb tcpip 5555
  • Slack集成Claude AI:企业级高效协作解决方案
  • 2026 上海浦东空压机上门维修服务商推荐|正规维保挑选参考 - 奔跑123
  • 2026年最新GEO优化收费标准与源头服务商选择指南 - 品牌报告
  • 淘宝新店用什么推广最好?
  • PHP实验性项目部署与测试全指南:从乱码名称到功能验证