类C代码风格

发布时间 2023-12-09 12:11:51作者: tqfx

格式化工具

推荐使用 clang-formatgit-clang-format 统一 C/C++/Objective-C 代码风格。

代码风格使用工程根目录下的 .clang-format 文件描述。

  • 在新增文件时,使用 clang-format 调整代码风格:
clang-format -i /path/to/files
  • 在修改文件时,使用 git-clang-format 调整新增部分的代码风格:
cd /path/to/repo
git-clang-format

代码风格

对于 C/C++/Objective-C 代码,个人使用 LLVM 代码风格。但是对下列项目作出调整:

项目 修改 解释
AccessModifierOffset -4 访问修饰符的位置
AlignEscapedNewlines Left 转义的换行符尽可能左对齐
AlignTrailingComments false 取消对齐尾随注释
AlwaysBreakTemplateDeclarations Yes 总是在 template 声明之后中断
BreakBeforeBraces Allman 总是在大括号之前中断
BreakInheritanceList BeforeComma 在逗号前断开继承列表
BreakConstructorInitializers BeforeComma 在逗号前中断构造函数初始化式
ColumnLimit 0 取消列限制
IndentWidth 4 缩进宽度
KeepEmptyLinesAtTheStartOfBlocks false 删除块开头的空行
ObjCBlockIndentWidth 4 用于 ObjC 块缩进的字符数
ReflowComments false 禁止修改注释
SortIncludes false 禁止排序 #include
SpaceBeforeCtorInitializerColon false 删除构造函数初始化器冒号之前的空格
SpaceBeforeInheritanceColon false 删除继承冒号之前的空格
SpacesInContainerLiterals false 删除容器字面量中的空格
TabWidth 4 制表位列数

参考

https://clang.llvm.org/docs/ClangFormatStyleOptions.html
https://github.com/tqfx/clang-format/blob/main/config/custom.yml
https://github.com/tqfx/clang-format/blob/main/config/attach.yml
https://github.com/tqfx/clang-format/blob/main/config/disable.yml