LLVM/clang-tidy静态分析:自定义规则与集成CI
请介绍 clang-tidy 的使用方法,包括如何配置 .clang-tidy 文件、常见的检查规则(modernize//performance//bugprone/*)、如何集成到 CMake 构建和 CI 流水线中。
回答
编译有声
clang-tidy 是 LLVM 的 C++ 静态分析工具。
基本用法:
# 单文件
clang-tidy main.cpp -- -std=c++20 -Iinclude
# CMake 集成(通过 compile_commands.json)
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
run-clang-tidy.py
# 自动修复
clang-tidy --fix main.cpp
.clang-tidy 配置:
Checks: '
-*,
modernize-*,
performance-*,
bugprone-*,
readability-*,
-readability-avoid-const-params-in-decls,
'
CheckOptions:
modernize-use-auto: {MinTypeNameLength: '5'}
WarningsAsErrors: 'bugprone-*'
常见检查分类:
modernize-*:C++11/14/17/20 现代化(use-auto, use-nullptr, use-override)。performance-*:性能问题(move-const-arg, inefficient-vector-operation)。bugprone-*:易错代码(suspicious-missing-comma, argument-comment)。clang-analyzer-*:深层分析(potential memory leak, dead store)。readability-*:可读性(braces-around-statements)。misc-*:杂项(const-correctness)。
CI 集成(GitHub Actions):
- name: clang-tidy
run: |
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -B build
run-clang-tidy -p build -j$(nproc)
高级:可使用 clang-tidy 插件编写自定义检查。