c++如何用LLVM开发工具 c++ Clang LibTooling入门【教程】

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),确保包含 clangToolingclangAST 等组件;
  • Windows:下载 LLVM 官方预编译包(含 libclang.dll 和头文件),或用 vcpkg:vcpkg install llvm:x64-windows
  • 验证是否就绪:检查路径下是否存在 clang/Tooling/CommonOptions.hlib/libclangTooling.a(或 .lib/.dylib)。

二、写第一个 LibTooling 工具:打印函数名

创建一个最简工具,读取 C++ 文件,遍历 AST 找出所有函数声明并输出名字:

1. 新建 print-funcs.cpp

#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"

using namespace clang; using namespace clang::tooling;

class FuncNameVisitor : public RecursiveASTVisitor { public: bool VisitFunctionDecl(FunctionDecl *D) { if (!D->isThisDeclarationADefinition()) return true; llvm::errs() << "Found function: " << D->getNameAsString() << "\n"; return true; } };

class FuncNameASTConsumer : public ASTConsumer { FuncNameVisitor Visitor; public: void HandleTranslationUnit(ASTContext &Context) override { Visitor.TraverseDecl(Context.getTranslationUnitDecl()); } };

class FuncNameAction : public ASTFrontendAction { public: std::unique_ptr CreateASTConsumer(CompilerInstance &CI, StringRef file) override { return std::make_unique(); } };

int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, "print-funcs"); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); return Tool.run(newFrontendActionFactory().get()); }

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);
  • 在回调中用 ReplacementsASTRewriter 修改源码,再通过 applyAllReplacements 写回文件。

例如:自动给无返回值函数末尾加 return;(仅示意逻辑):

auto funcMatcher = functionDecl(
    isDefinition(),
    returns(voidType()),
    unless(hasBody(returnStmt()))
).bind("func");

MatchFinder Finder; Finder.addMatcher(funcMatcher, new MyFixCallback()); // 自定义回调 Tool.run(newFrontendActionFactory(&Finder).get());

四、调试与常见坑

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() 批量构建。