一、Clang-Tidy 能做什么
Clang-Tidy 是 LLVM 的静态分析工具,在编译时分析代码中潜在的 Bug 和代码异味。和 GDB/Run-time sanitizer 不同,它不需要运行程序就能检测问题。
# 基本用法
clang-tidy --checks=* source.cpp -- -std=c++17
# 常用 check 组合
clang-tidy --checks=modernize-*,performance-*,bugprone-* source.cpp
二、它能抓到的问题
// 1. modernize —— 用现代 C++ 写法替代旧写法
int* ptr = new int(42); // warning: use auto rather than explicit type
auto* ptr = new int(42); // ✅ 推荐写法
// 2. performance —— 性能问题
std::vector<int> v;
for (int i = 0; i < v.size(); i++) { // warning: range-for loop is faster
foo(v[i]);
}
for (auto x : v) { // ✅ 推荐
foo(x);
}
// 3. bugprone —— 潜在的 Bug
int x = 1;
if (x = 42) { // warning: assignment in if condition, did you mean == ?
// ...
}
void foo(const std::string& s) {
std::cout << s.c_str() << std::endl; // warning: unnecessary .c_str() call
std::cout << s << std::endl; // ✅ 推荐
}
// 4. clang-analyzer —— 深层逻辑错误
int* get_ptr() {
int x = 42;
return &x; // warning: returning reference to local temporary
}
void test() {
int* p = get_ptr();
*p = 0; // Use-After-Free(栈变量已失效)
}
三、在 CMake 中集成
# CMakeLists.txt 中添加 clang-tidy 支持
# ccmake 时设置 -DCMAKE_CXX_CLANG_TIDY=clang-tidy
# 或者编辑 CMakeCache.txt:
# CMAKE_CXX_CLANG_TIDY:STRING=clang-tidy;-checks=modernize-*,performance-*,bugprone-*
# 效果:每次编译时自动运行 clang-tidy,警告出现在编译输出中
四、用 .clang-tidy 配置项目规则
# .clang-tidy
Checks: >
modernize-*,
performance-*,
bugprone-*,
readability-*,
-modernize-use-trailing-return-type, # 排除某个不想要的检查
WarningsAsErrors: >
bugprone-* # 把 Bug 相关的警告视为错误
CheckOptions:
{ key: readability-identifier-naming.ClassCase, value: CamelCase }
{ key: readability-identifier-naming.FunctionCase, value: camelBack }