在 C++ 代码上使用 clang-tidy
🌐 Using clang-tidy on C++ Code
[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) 是一个用于自动检查 C/C++/Objective-C 代码的工具,它可以检测风格违规、编程错误以及最佳实践。
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 在检查进程中也会占用大量内存,因此很容易出现内存不足的错误。因此,默认的作业数量为一个。
🌐 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.