I am using gdb to debug a C++ program.
I have this code:
int x = floor(sqrt(3));
and I want to view the value of x. However, gdb cl
Create your own 'global variable' and print the optimized out variable into this global variable. Make sure to remove these globals created by you after you are done with the debugging!
On high optimization levels, the compiler can eliminate intermediate values, as you have seen here. There are a number of options:
-O0 is certain to work (but will be quite a lot slower), -O1 might work okay as well.If you can't or don't want to disable optimization, then you can try declaring the variable as volatile. This is usually enough to make your compiler preserve the variable in the final code.
Alternatively, in recent GCC versions you can disable optimization for just a function, like this:
void my_function() __attribute__((optimize(0)))
{
int x = floor(sqrt(3));
}
When using reverse debugging, try to step back closer to the definition point of the variable
As shown at: What does <value optimized out> mean in gdb? it is often the case that within functions, the value of variables can be initially observed, and only later becomes <optimized out> as it is not needed anymore and the register containing it gets overwritten.
Therefore, if you are using some kind of reverse debugging such as Mozilla rr, which you will do all the time once you try it once, then one good bet is to try and step back closer to the point of definition/last usage of the variable with reverse-finish + reverse-next and see if you can observe it there.
This can be observed concretely with the example code shown at What does <value optimized out> mean in gdb? and has saved me a few times, especially when running the unoptimized program makes it take too long to reach the point of interest (which is unsurprising given the terribly inefficient assembly generated by -O0 as seen on that answer).