Why would I need this? 开发者_如何学GoThe location of a datum keeps changing because input data varies too much, so other than printing it, sleeping for 30 seconds so I can manually enter it into GDB, then continuing the program, it might be useful to just let the program tell GDB where to watch. But is such a thing possible?
You can get close; assuming for simplicity C/C++ language
Define a function that returns a reference to your datum to track:
// debug.h
extern "C" mydatastruct* GetDatumForDebug();
// debug.cpp
mydatastruct* GetDatumForDebug()
{
if (s_initialized)
return &some_complicated_address_lookup_perhaps_in_Cpp_or_java_orwhatever();
return (mydatastruct*) 0;
}
You can then subsequently just
(gdb) display GetDatumForDebug()
or even
(gdb) display GetDatumForDebug()->s
I assume it will be possible to use the result of GetDatumForDebug() in your debug watches, I'm not sure what you do/how you do that :)
Here is a working example, crammed in a single source (test.cpp) for speed: compile with g++ -g test.cpp -o test
:
static bool s_initialized = false;
struct mydatastruct { const char* s; };
static mydatastruct& some_complicated_address_lookup_perhaps_in_Cpp_or_java_orwhatever()
{
static mydatastruct s_instance = { "hello world" };
s_initialized = true;
return s_instance;
}
extern "C" mydatastruct* GetDatumForDebug();
// debug.cpp
mydatastruct* GetDatumForDebug()
{
if (s_initialized)
return &some_complicated_address_lookup_perhaps_in_Cpp_or_java_orwhatever();
return (mydatastruct*) 0;
}
int main()
{
// force initialize for demo purpose:
some_complicated_address_lookup_perhaps_in_Cpp_or_java_orwhatever();
return 42;
}
Automate gdb commands
Append the following to .gdbinit
in your working directory:
break main
run
call some_complicated_address_lookup_perhaps_in_Cpp_or_java_orwhatever()
display GetDatumForDebug()? GetDatumForDebug()->s : ""
This will automatically execute these commands on launching gdb in that directory
精彩评论