开发者

How do I track variable changes in gcc

Is it possible to track when where and how does a variable change?开发者_Go百科 I am coding in C using gcc on Linux


If you want to put some extra code inside your program that is run when a variable changes, then no - Standard C doesn't provide a way to do that. You have to find all the places in your program that could try to change the variable value and put some logging code in each and every one. You can make that more reliable by renaming the variable then fixing the points where compilation breaks, but that only works if you can recompile all the "client" code using the variable: if the variable is in a library with lots of other peoples' applications using it, that might not be practical.


Using get/set functions for access...

It's sometimes a good idea not to write code that directly uses a variable, but instead provide functions that get and set the value: then you can put some extra checks or logging inside those functions if it becomes useful some day. But, you don't want to do that everywhere or your code will be verbose and slower to run.


Polling checks for changes to the variable...

If it's good enough to check every now and then, then you can write some code that is triggered by a timer/alarm signal, or that runs in another thread, that checks on the variable periodically to see if it's changed, but that won't help you find out how it changed, and if the value changes but is changed back then you might miss those changes completely.


Using C++

If you compile your program under C++ (if possible, which for small programs may not even require any modifications to your code), then you can perhaps change the type of the data item in question and write an overloaded operator=() function that will be called when the variable is assigned to, and a operator old-type() conversion function so the places where the variable is used won't have to be modified:

template <typename T>
class Intercept
{
    Intercept(const T& t) : t_(t) { }
    T& operator=(const T& t) {
        std::cerr << "change " << t_ << " to " << t << '\n'; t_ = t; 
        return *this;
    }
    operator T&() { return t_; }
    operator const T&() const { return t_; }
    T t_;
};

Then change e.g.

int x;  // from
Intercept<int> x;  // to

Debuggers

As Drakosha says, if this is a debugging issue then you can run your program under the debugger until you resolve the issue.


There are memory break points in gdb. I think that's exactly what you are looking for:

Can I set a breakpoint on 'memory access' in GDB?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜