Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I view the value of an <optimized out> variable in C++?

Tags:

c++

g++

gdb

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?

like image 681
dangerChihuahua007 Avatar asked Feb 03 '12 04:02

dangerChihuahua007


People also ask

What is optimized value?

Customer Value Optimization (CVO) is a process to create a great customer journey and maximize the ROI for all marketing activities. It focuses on optimization throughout the customer lifecycle to improve brand and loyalty—and create customers for life.

How do I get optimized values in GDB?

To view the "optimized-out" value of a variable during debugging, you need to turn off gcccompiler optimization, either on a per-variable basis, or program-wide. If you are interested in a particular variable in gdb, you can delare the variable as "volatile" and recompile the code.

What is optimized out in GDB?

It means you compiled with e.g. gcc -O3 and the gcc optimiser found that some of your variables were redundant in some way that allowed them to be optimised away. In this particular case you appear to have three variables a, b, c with the same value and presumably they can all be aliassed to a single variable.

What does optimize code do?

Code optimization is any method of code modification to improve code quality and efficiency. A program may be optimized so that it becomes a smaller size, consumes less memory, executes more rapidly, or performs fewer input/output operations.


1 Answers

On high optimization levels, the compiler can eliminate intermediate values, as you have seen here. There are a number of options:

  • You can reduce the optimization level to make it easier for the debugger to keep track of things. -O0 is certain to work (but will be quite a lot slower), -O1 might work okay as well.
  • You can add some explicit print statements to log the output value.
  • You can also usually force the compiler to retain this specific value by making it volatile (but remember to un-make it volatile when you're done!). Note, however, that since control flow is also subject to alteration in optimized code, even if you can see the value of the variable, it may not be entirely clear what point in the code you're at when you're looking at the variable in question.
like image 57
bdonlan Avatar answered Sep 26 '22 11:09

bdonlan