【问题标题】:Check if variables are used in a cpp file检查cpp文件中是否使用了变量
【发布时间】:2019-01-05 19:30:35
【问题描述】:

我想让我的程序 (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++ 文件中使用?

更多信息:

  • 在我的例子中,a 变量总是双变量
  • 搜索声明“double a#”不是一个选项,因为变量可以通过其他方式声明 - 事实上,它们甚至不必声明,因为它们可能首先在编译时定义。
  • a 变量可以在其他函数中声明/使用,或者在 code.cpp 中作为全局变量
  • 无法搜索空格,因为算法还应检测“a3=a1*a2”中的三个变量

【问题讨论】:

  • 大多数编译器已经对未使用的变量或参数发出警告。我认为自己没有必要这样做。
  • 不打算警告未使用的变量或参数。我故意省略了代码的目的,因为它有点像兔子洞,但简而言之,我打算不声明 code.cpp 中的 a 变量,并通过命令行将它们声明为更大的动态编译的一部分我的项目。
  • 那么您应该遵循 Jesper 的回答中的建议,或者至少使用正则表达式执行您自己的方法,但请注意后者在解析正确的 c++ 语法方面仍然非常有限。

标签: c++ variables exists


【解决方案1】:

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

所以安装 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 Matcher 参考 http://clang.llvm.org/docs/LibASTMatchersReference.html

【讨论】:

    【解决方案2】:

    我会在Clanglibtooling 库之上构建这样一个工具,因为这使您可以轻松访问C++ 解析器,并且能够轻松搜索AST 以找到您想要的任何东西。也许更容易将其写为ClangTidy 检查。

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2010-09-22
      • 2021-04-21
      • 1970-01-01
      • 2015-05-01
      • 2012-01-20
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多