ZBLOG

Linux下的Centos系统使用 clang 格式和 git-clang 格式自动格式化C

在 Linux 下使用 clang-format 和 git-clang-format 也是非常方便的。

使用 clang-format 格式化代码:

  1. 安装 clang-format
sudo yum install clang-tools-extra -y
  1. 创建 .clang-format 文件

在项目根目录下创建一个名为 .clang-format 的文件,并加入以下内容:

---
Language:        Cpp
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands:   true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: AllExceptExternsAndLocalsWithArguments 
AllowShortIfStatementsOnASingleLine: NeverIncludeSeparatorsInReadabilityStyle 
AllowShortLoopsOnASingleLine: false 
AlwaysBreakAfterReturnType : None, exceptWhenReturnTypeIsVoid = AfterConst, AfterMutable, AfterStar, etc.
AlwaysBreakBeforeMultilineStrings : true # added for string format conversion.
AlwaysBreakTemplateDeclarations : true # added for template to fit in one line.
BinPackArguments                         : true # keep arguments together in one line if possible 
BinPackParameters                        : true # keep function parameters together in one line if possible 
BraceWrapping:
  AfterClass                 : true # add newline after class definition 
  AfterControlStatement      : true # add newline after if, for, while etc. 
  AfterEnum                  : true # add newline after enum definition 
  AfterFunction              : true # add newline after function definition 
  AfterNamespace             : true # add newline after namespace definition 
  AfterObjCDeclaration       : false
  AfterStruct                : true # add newline after struct definition 
  AfterUnion                 : true # add newline after union definition 
  BeforeCatch                : true # before catch statement
  BeforeElse                 : true # before else statement
  IndentBraces               : false # do not indent braces (keep them at the same level)
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit:     120
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat:   false
ExperimentalAutoDetectBinPacking        : false # experimental feature that keeps arguments and parameters together.
FixNamespaceComments                     : true # fix namespace comments to be aligned with the namespaces they describe.
ForEachMacros                          :
- foreach                   # accept boost-style foreach loop constructs.
- Q_FOREACH                 # accept Qt's Q_FOREACH macro.
IncludeCategories:
- Regex           : '^<.*\.h>'
    Priority        : -2    # priority of system headers is higher than others (0 by default).
- Regex           : '^<.*'
    Priority        : -1    #
- Regex           : '.*'
    Priority        : 1     #
IncludeIsMainRegex                      :
IndentCaseLabels                        :
IndentPPDirectives                       :
IndentWidth                              :
KeepEmptyLinesAtTheStartOfBlocks         :
MacroBlockBegin                          :
MacroBlockEnd                            :
MaxEmptyLinesToKeep                      :
NamespaceIndentation                     : None  
ObjCBinPackProtocolList                   : true # experimental feature that keeps Objective-C protocol lists together.
ObjCBlockIndentWidth                      : 4
ObjCSpaceAfterProperty                    : false
PointerAlignment: Right
ReflowComments                           : true # reflow comments to fit within the limit specified by ColumnLimit.
SortIncludes                             : true # sort include statements alphabetically.
SortUsingDeclarations                    : false # do not sort using declarations (causes issues with some compilers).
SpaceAfterCStyleCast                     : false #
SpaceBeforeAssignmentOperators           : true  # add space before assignment operators like =, += etc.
SpaceBeforeParens                        :
SpaceInEmptyParentheses                  :
SpacesBeforeTrailingComments             :
SpacesInAngles                           : false #
SpacesInContainerLiterals                : true  # add spaces between braces in container literals: vector<int> a = {1,2,3}; 
SpacesInCStyleCastParentheses             : false #
SpacesInParentheses                      :
Standard:        C11  
TabWidth:        4
UseTab:          Never

这是一个常见的配置文件,你也可以根据自己的需要进行修改。具体的各个选项含义可以参考 clang-format 官方文档。

  1. 格式化代码

在项目根目录下运行以下命令:

clang-format -i path/to/file.c

其中 path/to/file.c 是要格式化的文件路径。使用 -i 参数表示直接修改原文件。

使用 git-clang-format 格式化代码:

git-clang-format 是一个基于 git 的扩展,可以在 git commit 前自动格式化代码。

  1. 安装 git-clang-format
sudo yum install clang-tools-extra -y
  1. 配置 git-clang-format

运行以下命令进行配置:

git config --global clangFormat.binary clang-format
git config --global core.editor "git-clang-format -f"

这样就会在每次提交前使用 clang-format 格式化代码了。

注:需要注意的是,在使用 git-clang-format 时,会对整个文件进行格式化,因此可能会造成一些意想不到的影响。建议在提交前先检查修改的内容。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=6406

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?