clang libtooling-如何使用依赖关系

Clang LibTooling - How to use DependencyCollector

本文关键字:依赖 关系 何使用 libtooling- clang      更新时间:2023-10-16

我正在尝试使用工具中的clang的依赖项collector类来列出文件中的所有依赖项,以便说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;
}

该程序找不到任何内容。
如果有人能帮助我,那将是很棒的,因为在互联网上搜索数小时后我找不到答案。

问题在于,您用空体覆盖ExecuteAction()的CC_2方法。如果删除行:

void ExecuteAction() {}

一切都按预期工作。