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?

+28
c ++ g ++ gdb
Feb 03 2018-12-12T00:
source share
3 answers

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. -O0 probably works (but it will be much slower), -O1 can 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.
+33
Feb 03 2018-12-12T00
source share

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)); } 
+13
03 Feb '12 at 18:14
source share

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!

0
Apr 10 '13 at
source share



All Articles