Clang LibTooling - 如何使用DependencyCollector

时间:2017-09-18 13:13:48

标签: c++ include dependencies clang libtooling

我正在尝试在我的工具中使用Clang的DependencyCollector类来列出文件中的所有依赖项,让我们说test.cpp
这是我的计划:

#include "stdafx.h"
#include <iostream>
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/Utils.h"

using namespace std;
using namespace clang::tooling;
using namespace clang;
using namespace llvm;

static cl::OptionCategory MyToolCategory("my-tool options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp MoreHelp("\nMore help text...");

class myDependencyCollector : public DependencyCollector {
private:
public:
    bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, bool IsModuleFile, bool IsMissing) {
        if (Filename == "stdafx.h" || IsSystem) { 
            return false; 
        } else {
            return true;
        }
    }
    bool needSystemDependencies() {
        return false;
    }
};

class DependencyAction : public PreprocessOnlyAction {
private:
    myDependencyCollector *col;
public:
    virtual bool usesPreprocessOnly() const {
        return true;
    }
    bool BeginSourceFileAction(CompilerInstance &ci) {
        Preprocessor &pp = ci.getPreprocessor();
        col = new myDependencyCollector();
        col->attachToPreprocessor(pp);
        return true;
    }

    void ExecuteAction() {
    }

    virtual void EndSourceFileAction() {
        llvm::ArrayRef<string> arr = col->getDependencies();
        int size = arr.size();
        for (int i = 0; i < size; i = i+1) {
            cout << arr[i] << endl;
        }
    }
};

int main(int argc, const char **argv)
{
    CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
    ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
    int result = Tool.run(newFrontendActionFactory<DependencyAction>().get());
    return result;
}

现在,如果我运行该程序,例如文件test.cpp

#include <iostream>
#include "test.h"
void do_math(int *x) {
    *x += 5;
}

int main(void) {
    int result = -1, val = 4;
    do_math(&val);
    return result;
}

该程序未找到任何包含 如果有人可以帮助我,那将是很棒的,因为我在互联网上搜索数小时后无法找到答案。

0 个答案:

没有答案