簡體   English   中英

使用clang獲取類中的方法列表

[英]Get list of methods in class using clang

在常見的IDE(選擇一個)中,您經常會有一個大綱視圖,顯示特定類的方法列表。

假設我在IFoo.h中有一個C ++接口類,如下所示:

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

如何(以編程方式)我可以使用clang庫IFoo.h上面的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代碼(clang默認將*.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM