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 claims that x is "< optimized_out >". How do I view the value of x? Should I change my compiler flags?
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 claims that x is "< optimized_out >". How do I view the value of x? Should I change my compiler flags?
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:
<optimized out>
, as it was stored only in a register due to optimizations, and not on memory on the stack. So when it is not needed anymore, the register is likely to be reused and overwritten by another variable, and then the debug metadata informs GDB of that.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).
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!
With C++ in Visual Studio with the VisualGDB extension, I've seen class-scoped variables that are syntactically correct, but with the runtime variable inspection and hover text claiming the values are optimized out, even though they are actually not.
In order to view the value, prefixing the variable name with the class name in the quick watch or watch window resolved for me.
For example: the myvariable
value that appears to be optimized out in myclass
can be viewed with myclass::myvariable
.