检查cpp文件中是否使用了变量

Check if variables are used in a cpp file

我想让我的程序 (main.cpp) 读取一个 cpp 文件 (code.cpp),并确定是否使用了某些变量。这可以通过读取文件和搜索子字符串轻松完成,但是这有如下所述的不良缺点。

code.cpp

的内容
double a4 = 4.0;
int main() {
    double a1 = 1.0;
    double a2 = 2.0; 
    //a3 is inside comment. Therefore a3 does not exist
    double a33 = 3.0; //a33 exists. a3 does not exist
    string s = "a1a2a3"; //a3 still does not exist
    return 0;
}

main.cpp 的内容(我目前尝试解决此任务)

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    std::ifstream file;
    file.open("code.cpp");
    std::string s;
    while(std::getline(file,s)){
        if (s.find("a1") != std::string::npos)
            cout << "found a1" << endl;
        if (s.find("a2") != std::string::npos)
            cout << "found a2" << endl;
        if (s.find("a3") != std::string::npos)
            cout << "found a3 :(" << endl;
        if (s.find("a4") != std::string::npos)
            cout << "found a4" << endl;
    }
    return 0;
}

主执行的输出:

found a4
found a1
found a2
found a3 :(
found a3 :(
found a1
found a2
found a3 :(

main.cpp 不成功,因为它检测到 a3 是 code.cpp.

中使用的变量

是否有任何实用的方法来确定某些名称的变量是否存在或是否在 c++ 文件中使用?

更多信息:

我会在 Clang's libtooling library, since that gives you easy access to a C++ parser and the ability to easily search the AST for whatever your heart desires. Perhaps even easier would be to write it as a ClangTidy 检查的基础上构建这样一个工具。

正如 Jesper 提到的,您需要一个 C++ 解析器。要确定特定名称的变量是否存在或是否在 c++ 文件中使用,最简单的方法是使用 Clang AST Matcher,而不是自己实现一个工具。

所以安装 LLVM、Clang、Clang 工具并启动 clang-query:

$ clang-query yourcode.cpp
clang-query> match varDecl(hasName("a1"))
Match #1:
/home/yourcode.cpp:3:5: note: "root" binds here
    double a1 = 1.0;
    ^~~~~~~~~~~~~~~
1 match.
clang-query> match varDecl(hasName("a2"))
Match #1:
/home/yourcode.cpp:4:5: note: "root" binds here
    double a2 = 2.0; 
    ^~~~~~~~~~~~~~~
1 match.
clang-query> match varDecl(hasName("a3"))
0 matches.
clang-query> match varDecl(hasName("a4"))
Match #1:
/home/yourcode.cpp:1:1: note: "root" binds here
double a4 = 4.0;
^~~~~~~~~~~~~~~
1 match.

您可以做的远不止这些,请查看 AST 匹配器参考 http://clang.llvm.org/docs/LibASTMatchersReference.html