How to view the value of a <optimized out> variable in C ++?
I use gdb to debug a C ++ program.
I have this code:
int x = floor(sqrt(3)); and I want to see the value of x. However, gdb claims that x is "<optimized_out>". How to view x value? Should I change my compiler flags?
At high levels of optimization, the compiler can eliminate intermediate values, as you saw here. There are several options:
- You can reduce the level of optimization to make it easier for the debugger to track things.
-O0probably works (but it will be much slower),-O1can work fine. - You can add some explicit print instructions to register the output value.
- You can also force the compiler to keep this particular value by making it mutable (but remember to make it mutable when you're done!). Note, however, that since the control flow is also subject to change in optimized code, even if you can see the value of the variable, it may not be clear at what point in the code you are when you look at the variable in question.
If you cannot or do not want to turn off optimization, try declaring the variable as volatile . Usually this is enough for your compiler to save the variable in the final code.
Alternatively, in the latest versions of GCC, you can disable optimization only for a function, for example:
void my_function() __attribute__((optimize(0))) { int x = floor(sqrt(3)); } Create your own global variable and print the optimized variable in this global variable. Be sure to delete these global variables that you created after debugging is complete!