2

我试图在我的工具中使用 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;
}

该程序没有找到任何包含。
如果有人可以帮助我,那就太好了,因为在互联网上搜索了数小时后我无法找到答案。

4

1 回答 1

0

问题是你用一个空的主体覆盖了ExecuteAction()方法。class PreprocessOnlyAction如果删除该行:

void ExecuteAction() {}

一切都按预期工作。

于 2021-12-29T16:12:01.953 回答