【发布时间】: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++ 语法方面仍然非常有限。