前言
一大清早起来调试 CS2 的 C 源码。但是从官网上下载的课本源码格式化做得不好,阅读非常困难。于是尝试在网上找一下关于在 vscode 上格式化、调试 c 语言的工具。最终选定并实践以下工具。
0. 环境
- OS: MacOS
- IDE: vscode
- 格式化插件:clang-format
1. 步骤
1.1 brew 安装 clang-format
# brew install clang-format
安装完成后,先查看 clang-format 可执行文件
的位置。需要提供给 vscode 插件使用的。
➜ bin pwd
/usr/local/Cellar/clang-format/10.0.0/bin
➜ bin ls
clang-format git-clang-format
PS: brew 安装的软件默认都是在 /usr/local/Cellar
目录下。
1.2 vscode 安装 clang-format 插件
这个插件的 Readme 文档说明,需要指定 clang-format 执行目录。
Specifying the location of clang-format
This extension will attempt to find clang-format on your PATH. Alternatively, the clang-format executable can be specified in your vscode settings.json file:
{
"clang-format.executable": "/absolute/path/to/clang-format"
}
这时候,可以将步骤1.1拿到的路径,配置到 vscode 的插件中。
1.3 验证生效
int main(int argc, char *argv[])
{
int val = 12345;
if (argc > 1) {
if (argc > 1) {
val = strtol(argv[1], NULL, 0);
}
printf("calling test_show_bytes\n");
test_show_bytes(val);
} else {
printf("calling show_twocomp\n");
show_twocomp();
printf("Calling simple_show_a\n");
simple_show_a();
printf("Calling simple_show_b\n");
simple_show_b();
printf("Calling float_eg\n");
float_eg();
printf("Calling string_ueg\n");
string_ueg();
printf("Calling string_leg\n");
string_leg();
}
return 0;
}
选择一个格式可读性比较差的 c 文件,然后通过快捷键 shift + option + F
,格式化,得到如下格式。
int main(int argc, char *argv[]) {
int val = 12345;
if (argc > 1) {
if (argc > 1) {
val = strtol(argv[1], NULL, 0);
}
printf("calling test_show_bytes\n");
test_show_bytes(val);
}
else {
printf("calling show_twocomp\n");
show_twocomp();
printf("Calling simple_show_a\n");
simple_show_a();
printf("Calling simple_show_b\n");
simple_show_b();
printf("Calling float_eg\n");
float_eg();
printf("Calling string_ueg\n");
string_ueg();
printf("Calling string_leg\n");
string_leg();
}
return 0;
}
2 定制配置
clang-format 还允许开发者自行定制格式
2.1 在项目目录增加一个 .clang-format 的文件
2.2 增加配置
BasedOnStyle: LLVM
AccessModifierOffset: -4
IndentWidth: 4
ContinuationIndentWidth: 4
TabWidth: 4
#UseTab: ForIndentation
UseTab: Never
AllowShortIfStatementsOnASingleLine: false
ColumnLimit: 140
BreakBeforeBraces: Attach
AllowShortFunctionsOnASingleLine: Empty
BreakBeforeBraces: Custom
BraceWrapping:
BeforeElse: true
2.3 验证
重复步骤 1.3 即可。我自己在使用定制配置的时候,感觉更加合适一点。