libtooling是clang提供的c++ api,用于开发静态分析或代码改写工具,支持ast遍历、匹配与重写;需安装完整clang开发库,通过recursiveastvisitor或ast_matchers实现功能,注意编译参数、ast节点有效性及sourcelocation处理。

用 C++ 基于 LLVM/Clang 开发静态分析工具或代码改写工具,核心是 LibTooling —— 它是 Clang 提供的一套 C++ API,让你能以“宿主程序”方式加载源码、遍历 AST、匹配节点、修改或生成代码。不需要写插件、不依赖编译器内部构建流程,上手快、调试方便。
一、环境准备:安装 Clang 开发库
LibTooling 头文件和链接库需完整安装(不只是 clang 命令行)。推荐方式:
-
Linux/macOS:用包管理器安装
libclang-dev(Ubuntu/Debian)或llvm(macOS Homebrew),确保包含clangTooling、clangAST等组件; -
Windows:下载 LLVM 官方预编译包(含
libclang.dll和头文件),或用 vcpkg:vcpkg install llvm:x64-windows; - 验证是否就绪:检查路径下是否存在
clang/Tooling/CommonOptions.h和lib/libclangTooling.a(或 .lib/.dylib)。
二、写第一个 LibTooling 工具:打印函数名
创建一个最简工具,读取 C++ 文件,遍历 AST 找出所有函数声明并输出名字:
1. 新建 print-funcs.cpp:
立即学习“C++免费学习笔记(深入)”;
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "llvm/Support/CommandLine.h"
<p>using namespace clang;
using namespace clang::tooling;</p><p>class FuncNameVisitor : public RecursiveASTVisitor<FuncNameVisitor> {
public:
bool VisitFunctionDecl(FunctionDecl *D) {
if (!D->isThisDeclarationADefinition()) return true;
llvm::errs() << "Found function: " << D->getNameAsString() << "\n";
return true;
}
};</p><p>class FuncNameASTConsumer : public ASTConsumer {
FuncNameVisitor Visitor;
public:
void HandleTranslationUnit(ASTContext &Context) override {
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
}
};</p><p>class FuncNameAction : public ASTFrontendAction {
public:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef file) override {
return std::make_unique<FuncNameASTConsumer>();
}
};</p><p>int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, "print-funcs");
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
return Tool.run(newFrontendActionFactory<FuncNameAction>().get());
}</p>2. 编译(以 Ubuntu 为例):
clang++ -std=c++17 print-funcs.cpp \ `llvm-config --cxxflags --ldflags` \ `clang++ -xc++ -E -v /dev/null 2>&1 | sed -n 's/.*-I\(.*clang.*\)/-I\1/p' | head -1` \ -lclangTooling -lclangFrontend -lclangSerialization \ -lclangDriver -lclangParse -lclangSema -lclangAST \ -lclangLex -lclangBasic -lLLVM-*.so -o print-funcs
3. 运行:
./print-funcs test.cpp -- -x c++ -std=c++17
注意:-- 后是模拟 Clang 的编译参数,必须提供语言和标准,否则解析失败。
三、关键机制说明:AST 匹配与重写更实用的方式
手动写 RecursiveASTVisitor 灵活但繁琐。Clang 提供了更高层的 ast_matchers + ast_matchers::match 接口,配合 clang::tooling::fixit 可轻松实现模式化改写:
- 用
functionDecl()、hasName("foo")、hasBody(stmt())等 matcher 组合表达意图; - 用
MatchFinder注册 matcher 和回调类(继承MatchCallback); - 在回调中用
Replacements或ASTRewriter修改源码,再通过applyAllReplacements写回文件。
例如:自动给无返回值函数末尾加 return;(仅示意逻辑):
auto funcMatcher = functionDecl(
isDefinition(),
returns(voidType()),
unless(hasBody(returnStmt()))
).bind("func");
<p>MatchFinder Finder;
Finder.addMatcher(funcMatcher, new MyFixCallback()); // 自定义回调
Tool.run(newFrontendActionFactory(&Finder).get());</p>四、调试与常见坑
LibTooling 工具易出错,几个高频问题:
-
编译参数缺失:没传
-std=...或-I路径,导致预处理失败或 AST 不全;建议用compile_commands.json(由 CMake 生成)避免手动拼参; -
AST 节点为空:如
D->getBody()返回nullptr,因函数是声明而非定义,务必用isThisDeclarationADefinition()判断; -
字符串/SourceLocation 处理:不要直接用
toString(),优先用Lexer::getSourceText(CharSourceRange, Context.getSourceManager(), LangOptions)获取原始文本; -
多文件支持:默认只处理命令行列出的文件,若需递归扫描,自行遍历目录并调用
Tool.run(),或使用ClangTool::buildASTs()批量构建。











