Reputation: 6094
Not sure if feasible... I am reading a large software code, and sometimes feel lost when tracing how certain variable is accessed.
It would be great if there is tool/method to trace that.
More specifically, suppose I have the following class.
class A
{
public:
int _a;
};
...
and whenever
... = ...->_a;
during runtime, I would like to print out FILE and LINE. Thank you for the suggestion.
P.S., I could grep all "->_a" appearances, but that is also pretty hard to sort out.
Upvotes: 0
Views: 1600
Reputation: 12200
You can use a tool like OpenGrok or Source Navigator to find all occurrences. This is static analysis, not runtime, but easier than grep.
Upvotes: 0
Reputation: 1507
One of the most powerful tools to debug C code is GDB. For your specific need, you can make use of watch/awatch/rwatch commands in GDB to identify points when your variable is accessed (read/write). Once program execution stops at those points, you could use print
to either check or set the value of that variable.
Refer to this link for further clarifications.
Upvotes: 0
Reputation: 5080
Instead of:
class A
{
public:
int _a;
};
You could do something like this:
#include <iostream>
class Integer
{
public:
Integer(int value) : value(value)
{
}
operator int()
{
std::cout << "Integer called\n";
return value;
}
private:
int value;
};
class A
{
public:
A() : _a(5) {}
Integer _a;
};
int main(int argc, char *argv[])
{
A a;
std::cout << a._a << std::endl;
return 0;
}
Following your example:
Create a class and provide an operator for implicit conversion;
Substitute your member variable for this new class.
The implicit conversion operator will do the work.
It will print:
Integer called
5
A tip: never let a member variable be public. Always provide an accessor method.
Edit
Sorry, I forgot about FILE and LINE:
I didn't find a way to inject LINE or FILE because the implicit cast will be done at runtime while macro substitution under preprocessing.
What you can do it is to put a breakpoint at implicit conversion function, as pointed by @veer, and manually trace each calling.
Edit 2
At least it is possible to see the call stack at runtime.
On Linux this can be done through execinfo and on Windows through StackWalker.
Upvotes: 3