使用 clang 获取类中的方法列表

Get list of methods in class using clang

本文关键字:方法 列表 clang 获取 使用      更新时间:2023-10-16

在常见的 IDE(选择一个)中,您通常会有一个大纲视图,显示特定类的方法列表。

假设我在IFoo.h中有一个C++接口类,如下所示:

#ifndef IFOO_H_
#define IFOO_H_
class IFoo { 
    public:
        virtual ~IFoo() {}
        virtual void bar() = 0;
};
#endif

如何(以编程方式)使用 clang 库为上面的IFoo.h文件获取这样的 IDE 大纲列表?首先,如果我能获得函数名称列表,这将有所帮助。

我特别打算使用 clang,所以任何关于如何使用 clang 分析我的头文件的帮助将不胜感激。

同时,我将在这里查看 clang 教程:https://github.com/loarabia/Clang-tutorial

提前感谢您的帮助。

我 http://clang.llvm.org/docs/LibASTMatchersTutorial.html 浏览了本教程,并在那里发现了一些非常有用的东西,这就是我想出的:

我不得不将我的文件从 IFoo.h 重命名为 IFoo.hpp 才能被检测为 Cxx 而不是 C 代码。

我必须-x c++调用我的程序,以使我的IFoo.h文件被识别为C++代码而不是 C 代码(默认情况下*.h文件解释为 C:

~/Development/llvm-build/bin/mytool ~/IFoo.h -- -x c++

这是我从提供的类中转储所有虚函数的代码:

// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/ASTMatchers/ASTMatchers.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <cstdio>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
DeclarationMatcher methodMatcher = methodDecl(isVirtual()).bind("methods");
class MethodPrinter : public MatchFinder::MatchCallback {
public :
  virtual void run(const MatchFinder::MatchResult &Result) {
    if (const CXXMethodDecl *md = Result.Nodes.getNodeAs<clang::CXXMethodDecl>("methods")) {    
      md->dump();
    }
  }
};
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("nMore help text...");
int main(int argc, const char **argv) {    
  cl::OptionCategory cat("myname", "mydescription");
  CommonOptionsParser optionsParser(argc, argv, cat, 0);    
  ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());
  MethodPrinter printer;
  MatchFinder finder;
  finder.addMatcher(methodMatcher, &printer);
  return tool.run(newFrontendActionFactory(&finder));
}

传递IFoo.h文件时,输出如下所示:

CXXDestructorDecl 0x1709c30 <~/IFoo.h:5:3, col:20> ~IFoo 'void (void)' virtual
`-CompoundStmt 0x1758128 <col:19, col:20>
CXXMethodDecl 0x1757e60 <~/IFoo.h:6:3, col:24> bar 'void (void)' virtual pure