In gdb how can I discover the value of a variable which displays as optimized out? Presumably the value is being stored in a register, how can I find out which one? Given this simple program (copied from the website named below).
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int foo = rand();
printf("foo is %d\n", foo++);
return foo;
}
Compile with optimization.
gcc -O3 -g optimized.c
gdb a.out
Run GDB
(gdb) print foo
$1 = <optimized out>
What is going on? The variable foo
must exist somewhere but how do I find its value or where it is stored?
I found a page which explains in detail how the DWARF debug information works for optimized code https://undo.io/resources/gdb-watchpoint/build-for-debug-in-gdb. Using the suggestions there I could eventually find the register assigned to foo
but it's rather painful.
How can I get gdb to tell me which register to watch?
I tried compiling with -g3 but that didn't help.
I tried a few commands in gdb which also didn't help.
ptype foo
info locals
print &foo