So basically you want to log some variables when they are written to/read from/passed to functions etc?
Doing this with compiled C is difficult, as mentioned, especially if you are optimising your executable (-0n on the compile statement), in which case some of the variables can disappear completely, or get re-used by other variables.
Using GDB
Having said that, I know gdb can log variable access and that sort of stuff. If you were to write a python script (see http://sourceware.org/gdb/onlinedocs/gdb/Python.html), you should be able to write a script to log variable content.
See this question for more: Do specific action when certain breakpoint hits in gdb
On demand only, using pre-compiler scripting
Alternatively, if you just wanted to do it on demand, you'd be better off using a pre-processing script to add in custom macro's or similar, using a csv file as input:
for each line in CSV:
read variable_name, file_name, variable_type
find all occurrences of variable_name in file_name
for each occurrence
insert printf(....)
On demand only, using macros
Good luck. There isn't a nice way to do it, because you'd generally need some sort of lookup, and you'd need a way of selectively outputting variables to your print function. In some cases you could do something like:
static char _LOGGED_VAR_001 = 'z';
static char _LOGGED_VAR_002 = 'z';
#define cMyVar _LOGGED_VAR_001
#define LOG_ALL_VARS() printf("Vals: %c, %c", _LOGGED_VAR_001, _LOGGED_VAR_002)
void myFunc()
{
char cMyVar; // Gets macro'd to _LOGGED_VAR_001 with LOCAL scope
cMyVar = 'a'; // LOCAL scope _LOGGED_VAR_001 becomes 'a'
LOG_ALL_VARS(); // At this point you print out the LOCAL _LOGGED_VAR_001
// and the global _LOGGED_VAR_002
}
You would get Vals: a, z
This is pretty ugly, would only work for variables with local scope, messes round with memory consumption, could be error prone and is generally a bad idea.
On demand, heap/stack dump
If you have enough storage, you could dump all your memory on demand to a file. This probably wouldn't be very portable, depending on how it was done. I'm not sure how to do it though, in a reliable manner.
Recommendation
Use GDB for design-time diagnostics. It's what it's designed for :)
For (e.g.) analysing released code (automated bug reports), a full dump and then analysis at will might be relevant.