.clang-format

本文详细介绍了一套针对C++代码的格式规范设置方案,包括缩进、换行、括号位置等细节调整,旨在提高代码可读性和一致性。此外还涉及了模板声明、注释格式、字符串处理等方面的具体配置。
---
Language:        Cpp
# BasedOnStyle:  Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AlignEscapedNewlines: Left
AlignEscapedNewlinesLeft: true
AlignOperands:   true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:   
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false
#  SplitEmptyFunctionBody: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
#BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
#BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     148
CommentPragmas:  '^ IWYU pragma:'
#CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
#FixNamespaceComments: true
ForEachMacros:   [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories: 
  - Regex:           '^<.*\.h>'
    Priority:        1
  - Regex:           '^<.*'
    Priority:        2
  - Regex:           '.*'
    Priority:        3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentWidth:     4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
#PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments:  true
SortIncludes:    true
SpaceAfterCStyleCast: false
#SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles:  false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard:        Auto
TabWidth:        4
UseTab:          Never
...

`.clang-format` 是一个用于格式化 C、C++、Java、JavaScript、Objective-C 等代码的配置文件,由 `clang-format` 工具读取并根据配置规则自动格式化代码。 --- ## ✅ 一、基本使用步骤 ### 1. 安装 clang-format 确保你已经安装了 `clang-format`,以下是不同系统的安装方式: - **Ubuntu/Debian**: ```bash sudo apt install clang-format ``` - **macOS (Homebrew)**: ```bash brew install clang-format ``` - **Windows (使用 vcpkg)**: ```powershell vcpkg install clang-format ``` 或者安装 [LLVM 官方包](https://releases.llvm.org/) --- ### 2. 创建 `.clang-format` 文件 你可以手动创建 `.clang-format` 文件放在项目的根目录中,或使用命令生成一个默认配置: ```bash clang-format -style=LLVM -dump-config > .clang-format ``` 你也可以使用其他风格,如: ```bash clang-format -style=Google -dump-config > .clang-format clang-format -style=Chromium -dump-config > .clang-format clang-format -style=Mozilla -dump-config > .clang-format clang-format -style=WebKit -dump-config > .clang-format ``` --- ### 3. 示例 `.clang-format` 文件(Google 风格) ```yaml BasedOnStyle: Google IndentWidth: 4 TabWidth: 4 UseTab: Never ColumnLimit: 100 BraceWrapping: AfterControlStatement: Always AfterEnum: false AfterFunction: false AfterStruct: false AfterUnion: false BeforeElse: true SpaceBeforeAssignmentOperators: true PointerAlignment: Right ``` --- ## ✅ 二、在命令行中使用 `.clang-format` ### 1. 格式化单个文件并输出到终端 ```bash clang-format your_file.cpp ``` ### 2. 直接修改文件内容(in-place) ```bash clang-format -i your_file.cpp ``` ### 3. 格式化整个目录中的所有 `.cpp` 和 `.h` 文件 ```bash find . -name "*.cpp" -o -name "*.h" | xargs clang-format -i ``` --- ## ✅ 三、在 VSCode 中使用 `.clang-format` ### 1. 安装插件 推荐使用插件:`xaver.clang-format` ### 2. 设置 VSCode 使用 `.clang-format` 在 `settings.json` 中添加以下配置: ```json { "[c]": { "editor.defaultFormatter": "xaver.clang-format" }, "[cpp]": { "editor.defaultFormatter": "xaver.clang-format" }, "editor.formatOnSave": true } ``` 这样保存文件时会自动格式化。 --- ## ✅ 四、常用配置选项说明 | 配置项 | 含义 | |--------|------| | `BasedOnStyle` | 基于的预设风格(如 Google、LLVM) | | `IndentWidth` | 缩进宽度 | | `UseTab` | 是否使用 Tab(Never, ForIndentation, ForContinuationAndIndentation) | | `ColumnLimit` | 每行最大字符数 | | `BraceWrapping.AfterFunction` | 函数大括号是否换行 | | `PointerAlignment` | 指针符号对齐方式(Left, Middle, Right) | | `AllowShortIfStatementsOnASingleLine` | 是否允许单行 if 语句 | | `SpaceBeforeAssignmentOperators` | 赋值操作符前是否加空格 | --- ## ✅ 五、在 Git 中使用 clang-format(可选) 你可以设置 Git 的 pre-commit 钩子,在提交前自动格式化代码: ```bash #!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. exec git diff --cached --name-only | grep -E '\.(c|cpp|h|hpp)$' | xargs clang-format -i ``` 将上面内容保存为 `.git/hooks/pre-commit`,并赋予执行权限: ```bash chmod +x .git/hooks/pre-commit ``` --- ## ✅ 六、总结 | 操作 | 命令/方式 | |------|-----------| | 创建 `.clang-format` | `clang-format -style=Google -dump-config > .clang-format` | | 格式化单个文件 | `clang-format your_file.cpp` | | 修改文件内容 | `clang-format -i your_file.cpp` | | VSCode 中使用 | 安装插件 + 设置默认格式化器 | | Git 提交前自动格式化 | 使用 `pre-commit` 钩子 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值