Home > OS >  Can we watch a read/write of/to a variable in C
Can we watch a read/write of/to a variable in C

Time:03-29

I have started learning about templates in C and am wondering if there is a way to say print out all the read and write to a particular variable just like we can do in CMake. For example, CMake has variable_watch() which is used to log all attempts to read or modify a variable.

So my question is that is there a way to do this in C . If there is no built-in way(provided by the standard C ), then will it be possible to implement it somehow(if so, how?). I mean, if CMake can have this feature then maybe C too. Maybe we can make use of template metaprogramming or something else.

CodePudding user response:

No, you cannot do it in C without wrapping your variable in something else that logs for you.

But it is possible to do what you need when you are debugging your code written in C using hardware breakpoints. You can use watch in gdb to check accesses to your variable. You can check it here or here. These types of breakpoints are available in Visual Studio too.

CodePudding user response:

Although C does not let you attach functionality to reads and/or assignments of variables of built-in types, it has enough features to let you build this functionality for user-defined types.

Specifically, C lets you overload assignment and conversion operators. You can build your own template type, say, Watched<T>, which has an assignment taking values of type T and an implicit conversion operator to T. It could also take optional ReadWatcher<T> and/or a WriteWatcher<T> functions, and call the ReadWatcher<T> from the conversion operator, and WriteWatcher<T> from the assignment operator.

CodePudding user response:

Instead of printing, use your debugger for that. Most debuggers support a special breakpoint that is triggered when the variable is read/written to.

  •  Tags:  
  • c
  • Related