使用 clang 从 C/C++ 头文件中提取函数声明

Extracting function declarations from a C/C++ header file using clang

我有以下递归 AST 访问者实现。

class ExampleVisitor : public clang::RecursiveASTVisitor<ExampleVisitor>{
private:
    clang::ASTContext* ast_context_; // used for getting additional AST info

public:
    explicit ExampleVisitor(clang::CompilerInstance* ci) 
      : ast_context_(&(ci->getASTContext())) // initialize private members

virtual bool VisitFunctionDecl(clang::FunctionDecl* func)
{
    numFunctions++;
    foo(func);  
    return true;
}};

函数 foo 打印给定输入文件的已声明函数的名称。

在此实现中,foo 打印输入文件中声明的函数,并从包含的头文件中转储所有函数声明。我如何修改此代码以仅打印给定输入文件中声明的函数?

尝试使用SourceManager来判断FunctionDecl是否在翻译单元的主文件中:

virtual bool VisitFunctionDecl(clang::FunctionDecl* func)
{
  clang::SourceManager &sm(ast_context_->getSourceManager());
  bool const inMainFile(
    sm.isInMainFile(sm.getExpansionLoc(func->getLocStart())));
  if(inMainFile){
    numFunctions++;
    foo(func);
  }
  else{
    std::cout << "Skipping '" << func->getNameAsString() 
      << "' not in main file\n";
  }  
  return true;
}};

碰巧知道有个AST Matcher叫isExpansionInMainFile。我从 cfe-3.9.0.src/include/clang/ASTMatchers/ASTMatchers.h 第 209-14.

行中那个匹配器的源代码中获取了上面的代码