clang-format使用
1. clang-format简介
Clang-Format可用于格式化(排版)多种不同语言的代码。
其自带的排版格式主要有:LLVM, Google, Chromium, Mozilla, WebKit等; 利用style参数配置风格。
通过编写 .clang-format 文件,可以实现代码风格的配置。
2. clang-format的使用
2.1 clang-format中.clang-format file
我们可以自定制代码风格约束,通过一下命令进行使用:
注意:file不是 .clang-format file的路径,就是file关键字;说明使用 the .clang-format file located in the closest parent directory of the input file. clang-format的设置进行代码约束;其他选项:-style=LLVM, Google, Chromium, Mozilla, WebKit
而.clang-format file由一下命令生成:生成google风格的clang-format配置文件
- clang-format -style=google -dump-config > .clang-format
复制代码 第二种方法配置:也可以通过设置key:value的方式进行
如:
- clang-format -style="{BasedOnStyle: llvm, IndentWidth:8} ..."
复制代码 2.2 示例:配置google的代码风格
- #1) 生成.clang-format文件
- clang-format -style=google -dump-config > .clang-format
- # 2) 配置.clang-format: 参考:https://clang.llvm.org/docs/ClangFormatStyleOptions.html
- # 3)通过.clang-format文件,进行代码风格约束
- # 格式化结果打印到中断
- clang-format -style=file code.cpp
- # 直接修改文件
- clang-format -style=file -i code.cpp
复制代码 2.3 vscode clang-format配置
3. clang-format 中 .clang-format file配置(yaml格式)
3.1 配置多个语言的约束
- ---
- # We'll use defaults from the LLVM style, but with 4 columns indentation.
- BasedOnStyle: LLVM
- IndentWidth: 4
- ---
- # C++
- Language: Cpp
- # Force pointers to the type for C++.
- DerivePointerAlignment: false
- PointerAlignment: Left
- ---
- Language: JavaScript
- # Use 100 columns for JS.
- ColumnLimit: 100
- ---
- Language: Proto
- # Don't format .proto files.
- DisableFormat: true
- ---
- Language: CSharp
- # Use 100 columns for C#.
- ColumnLimit: 100
- ...
复制代码 3.2 将某段代码忽略format
- int formatted_code;
- // clang-format off
- void unformatted_code ;
- // clang-format on
- void formatted_code_again;
复制代码 3.3 对齐方式

3.4 数组的左右对其设置
实际None设置为false;
注意:clang-format的版本,只有13是支持的
13版本前不支持

3.5 连续赋值语句的格式设置,是否等号对齐
根据下面的示例可以清楚的设置不同的格式情况;
注意:clang-format的版本,只有13是支持的
13版本前只支持true/false


3.6 AlignConsecutiveBitFields


3.7 AlignConsecutiveDeclarations
与AlignConsecutiveAssignments一样配置; 将声明语句与赋值语句对齐
3.8 宏的对齐AlignConsecutiveMacros


3.9 AlignEscapedNewlines(对齐选项中的反斜杠转义换行符)

3.10 对齐操作符

3.11 尾部注释格式

3.12 函数调用

3.13 函数对齐

根据需要设定不同的配置:
具体说明:https://clang.llvm.org/docs/ClangFormatStyleOptions.html
参考文献
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |