Modern compilers such as gcc are able to perform various optimizations based on syntax and semantic analysis of the code at compile time. The goal of such optimizations is to improve program execution speed and/or reduce binary size, and they typically come with the cost of extra compilation time or reduced debuggability of the program.
The <value optimized out> message in gdb is one symptom of such compiler optimizations. To view the "optimized-out" value of a variable during debugging, you need to turn off gcc compiler optimization, either on a per-variable basis, or program-wide, as described below.
Solution One: Turn-off Compiler Optimization on a Per-variable Basis
If you are interested in a particular variable in gdb, you can declare the variable as "volatile" and recompile the code. This will make the compiler turn off compiler optimization for that variable.
volatile int quantity = 0;
If you declare a variable as volatile, it means that the variable can be modified externally (e.g., by the operating system, a signal handler, or hardware interrupt, etc). This essentially tells the compiler that the variable's value in memory can change at any time. Thus the compiler must not perform any optimization on the variable, which makes the variable accessible to gdb debugger as well.
Solution Two: Turn-off Compiler Optimization for the Entire Program
Another option to see all <optimized out> variables in gdb is of course disabling gcc optimization altogether.
Look for compilation flags (e.g., in CFLAGS) in your Makefile. You will find something like '-O1', '-O2' or '-O3', which defines various levels of gcc optimization. Remove this flag, or change it to '-O0'.
For example, change:
CFLAGS = -g -O2 -DSF_VISIBILITY -fvisibility=hidden -fno-strict-aliasing -Wall
CFLAGS = -g -O0 -DSF_VISIBILITY -fvisibility=hidden -fno-strict-aliasing -Wall
This will reduce compilation time, and allows gdb to inspect the program properly, but at the cost of possibly reduced run-time program performance.
Subscribe to Ask Xmodulo
Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!