Skip to main content

在 C++ 代码上使用 clang-tidy

¥Using clang-tidy on C++ Code

clang-tidy 是一个自动检查 C/C++/Objective-C 代码是否有样式违规、编程错误和最佳实践的工具。

¥clang-tidy is a tool to automatically check C/C++/Objective-C code for style violations, programming errors, and best practices.

Electron 的 clang-tidy 集成作为 linter 脚本提供,可以与 npm run lint:clang-tidy 一起运行。当 clang-tidy 检查磁盘上的文件时,你需要构建 Electron,以便它知道使用了哪些编译器标志。脚本 --output-dir 有一个必需的选项,它告诉脚本从哪个构建目录中提取编译信息。典型的用法是:npm run lint:clang-tidy --out-dir ../out/Testing

¥Electron's clang-tidy integration is provided as a linter script which can be run with npm run lint:clang-tidy. While clang-tidy checks your on-disk files, you need to have built Electron so that it knows which compiler flags were used. There is one required option for the script --output-dir, which tells the script which build directory to pull the compilation information from. A typical usage would be: npm run lint:clang-tidy --out-dir ../out/Testing

如果未提供文件名,将检查所有 C/C++/Objective-C 文件。你可以通过在选项后传递文件名来提供要检查的文件列表:npm run lint:clang-tidy --out-dir ../out/Testing shell/browser/api/electron_api_app.cc

¥With no filenames provided, all C/C++/Objective-C files will be checked. You can provide a list of files to be checked by passing the filenames after the options: npm run lint:clang-tidy --out-dir ../out/Testing shell/browser/api/electron_api_app.cc

虽然 clang-tidy长名单 种可能的检查,但在 Electron 中,默认情况下仅启用少数检查。目前 Electron 没有 .clang-tidy 配置,因此 clang-tidy 会在 src/.clang-tidy 处找到来自 Chromium 的配置,并使用 Chromium 启用的检查。你可以使用 --checks= 选项更改运行哪些检查。这会直接传递到 clang-tidy,因此请参阅其文档以获取完整详细信息。可以使用通配符,并且可以通过添加前缀 - 来禁用检查。默认情况下,列出的任何检查都会添加到 .clang-tidy 中的检查中,因此,如果你想将检查限制为特定检查,你应该首先排除所有检查,然后添加回你想要的检查,例如 --checks=-*,performance*

¥While clang-tidy has a long list of possible checks, in Electron only a few are enabled by default. At the moment Electron doesn't have a .clang-tidy config, so clang-tidy will find the one from Chromium at src/.clang-tidy and use the checks which Chromium has enabled. You can change which checks are run by using the --checks= option. This is passed straight through to clang-tidy, so see its documentation for full details. Wildcards can be used, and checks can be disabled by prefixing a -. By default any checks listed are added to those in .clang-tidy, so if you'd like to limit the checks to specific ones you should first exclude all checks then add back what you want, like --checks=-*,performance*.

运行 clang-tidy 相当慢 - 它在内部编译每个文件,然后运行检查,因此它总是比编译慢一些。虽然你可以使用 --jobs|-j 选项使用并行运行来加速它,但 clang-tidy 在检查期间也会使用大量内存,因此很容易遇到内存不足错误。因此,默认的作业数量为 1。

¥Running clang-tidy is rather slow - internally it compiles each file and then runs the checks so it will always be some factor slower than compilation. While you can use parallel runs to speed it up using the --jobs|-j option, clang-tidy also uses a lot of memory during its checks, so it can easily run into out-of-memory errors. As such the default number of jobs is one.