How to print "optimized out" value in gdb

Last updated on August 29, 2020 by Dan Nanni

Question: I was debugging a program with gdb debugger. When I tried to print the value of a variable while tracing a function call, gdb says <value optimized out>, not displaying the value. How can I show the value of an <optimized out> variable in gdb?

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.

(gdb) p quantity
$8 = <optimized out>

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.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean