2014-02-19 23 views
8

在常見的IDE中(選擇一個),您經常會看到大綱視圖,向您顯示特定課程的方法列表。使用clang獲取課堂上的方法列表

假設我有IFoo.h C++接口類,看起來像這樣:

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

如何(在程序上)我可以得到這樣一個IDE大綱列表我IFoo.h文件上面使用也許鐺庫?首先,如果我能得到一個功能名稱列表,這將有所幫助。

我特意打算使用clang,所以任何關於如何用clang來分析我的頭文件的幫助都會很感激。

同時我會看看鐺教程這裏:https://github.com/loarabia/Clang-tutorial

在此先感謝您的幫助。

回答

12

我通過本教程http://clang.llvm.org/docs/LibASTMatchersTutorial.html去了,在那裏發現了一些非常有用的東西,這是我想出了:

我有我的文件重命名從 IFoo.hIFoo.hpp爲CXX進行檢測,而不是C代碼。

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

這是我的代碼轉儲:

我不得不打電話給我的程序與-x c++有我IFoo.h文件被識別爲C++代碼,而不是C代碼(鐺默認解釋*.h文件爲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 
+0

您是否研究過如何檢查特定訪問級別的方法?我不確定如何檢查公共方法。具體來說,我需要最後一個公共方法的位置。 – Lucas

+1

我會告訴你如何在今天晚上或明天早上回到我的電腦時執行此操作。我現在手邊只有一部手機。 –

+0

我在這裏發佈了這個問題:http://stackoverflow.com/questions/24564494/clang-retrieving-public-methods如果你想回答。謝謝! – Lucas