I desire to have my program (main.cpp) read a cpp file (code.cpp), and determine whether certain variables are used. This could easily be done by reading the file and searching for substrings, but this has undesired drawbacks as explained below.
Content of 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;
}
Content of main.cpp (my current attempt for solving this task)
#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;
}
Output from main execution:
found a4
found a1
found a2
found a3 :(
found a3 :(
found a1
found a2
found a3 :(
main.cpp is unsuccessful because it detects a3 being a variable used in code.cpp.
Is there any practical method to determine whether variables by certain names exist or are used in a c++ file?
Further information:
- In my case, the a-variables are always double
- Searching for the declaration "double a#" is not an option, because the variable may be declared by other means - in fact, they don't even have to be declared as they may first be defined on compilation.
- the a-variables may be declared/used in other other functions or as globals in code.cpp
- It is not possible to search for spaces because the algorithm should also detect the three variables in "a3=a1*a2"