Skip to content
systemcoding.dev
Debugging

Debug Optimised Builds With -Og and -fvar-tracking

Why GDB shows optimized out and jumps lines at -O2, how GCC -Og and variable tracking keep more values, and what to do when you must debug the real build.

7 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, C and LLVM logos.

The first thing that goes wrong when you debug a release build is that GDB stops being honest-looking. A variable you can see in the source prints as <optimized out>. next jumps from line 13 to line 12 and back to 14. A breakpoint on a small function never fires, because the function no longer exists as a call. None of this is a GDB bug. Optimisation rearranges the program so that the source and the machine code no longer correspond line by line, and the debug information can only describe what is left. This post explains what the compiler changes, what GCC's -Og level and its variable-tracking options do to help, how to read the remaining gaps, and which build flags to choose when the bug only appears in the optimised build. GCC 14 and GDB 16.3 on x86-64 Linux are the reference.

The program

A loop sums a small linear function through a helper that the compiler will inline.

opt.cc
#include <stdio.h>

static int scale(int x, int k)
{
    int t = x * k;
    return t + 1;
}

int main(int argc, char **argv)
{
    (void)argv;
    int total = 0;
    for (int i = 0; i < argc + 3; i++)
        total += scale(i, 5);
    printf("%d\n", total);
    return 0;
}

Run with no arguments, argc is 1, so the loop runs for i from 0 to 3. The helper returns 5i + 1, giving 1, 6, 11 and 16, and the total is 34. The program prints 34. It is correct at every optimisation level, which is the point: what changes is how well you can watch it.

What -O2 does to the picture

At -O0, every source variable lives in a stack slot for its whole life, and every line has its own instructions in source order. At -O2, GCC will do the following to this program, among other things: inline scale into main, so the call disappears; fold t = x * k; return t + 1 into one arithmetic expression, so t is never stored anywhere; keep i and total in registers and perhaps replace the multiplication with additions, as i * 5 becomes a running value that grows by 5 each iteration; and reorder instructions so the loop test and body interleave.

You can see the effect without running anything, by looking at what the debugger is able to say. In a typical session at -O2 -g, the loop line prints only partial information.

Text
(gdb) break scale
Breakpoint 1 at 0x1060: scale. (2 locations)
(gdb) run
Starting program: /home/dev/opt

Breakpoint 1, scale (x=<optimized out>, k=<optimized out>) at opt.c:5
5	    int t = x * k;
(gdb) print t
$1 = <optimized out>
(gdb) print k
$2 = <optimized out>

Two things are worth reading closely. The breakpoint has two locations, because GDB found the inlined copies of scale and set a breakpoint in each one; that is GDB handling inlined functions properly, and the number of locations is how many copies the compiler made. And x and k print as <optimized out>: the DWARF for the inlined instance has no location for them at this address, because k is a constant 5 that was folded into an instruction and x is in a register the compiler reused. The exact output depends on the compiler's choices, so take the message form, not the addresses, as the fixed part.

What <optimized out> means

The message does not mean the variable has no value. It means the debug information does not say where the value is at the current instruction. DWARF describes a variable's location with either a single expression, valid for the whole function, or a location list: a table mapping ranges of program counter values to places, "in rax from here to here, at rbp-20 from there to there, nowhere after that". At -O0 a single stack offset is enough. Optimised code needs a list, and the list has gaps where the compiler dropped the value because it was dead or where it computed something else in that register.

GCC's switch for building location lists is -fvar-tracking, enabled whenever you use -g with optimisation, and its companion -fvar-tracking-assignments, also on by default with -g at -O1 and above. The second one tracks assignments through the optimisers so a variable's value is carried through changes in the code, and it is the reason modern GCC keeps more values than GCC 4.4 did. You do not usually have to turn either on. The useful thing to know is that they exist, and that -fno-var-tracking is sometimes added to a build to cut compile time on very large files, which makes the debugging worse.

-Og: optimise for the debugging experience

GCC 4.8 added -Og. The manual describes it as optimisation that does not interfere with debugging: it enables the passes that make the code faster without destroying the correspondence between source and machine code, and it leaves out the ones that do the most damage. In practice it keeps most variables readable, keeps inlining minimal and keeps lines in source order, while still producing code noticeably closer to -O1 than -O0.

Shell
gcc -g -Og -Wall -Wextra -o opt_og opt.c
gdb -q ./opt_og
Text
(gdb) break 13
Breakpoint 1 at 0x1040: file opt.c, line 13.
(gdb) run
Starting program: /home/dev/opt_og

Breakpoint 1, main (argc=1, argv=0x7fffffffe0f8) at opt.c:13
13	        total += scale(i, 5);
(gdb) print i
$1 = 0
(gdb) print total
$2 = 0
(gdb) next
12	    for (int i = 0; i < argc + 3; i++)
(gdb) print total
$3 = 1

At -Og, i and total print, and a step shows total change by 1 after the first call, as the source says. The helper was likely still inlined, since inlining one-line static functions is cheap and does not harm the line mapping much, but its parameters are tracked where the compiler kept them. The exact register choices vary. -Og is the right default for a debug build of anything big enough that -O0 is too slow to run, which includes games, databases and embedded firmware where -O0 will not fit in flash.

Making the optimised build more honest

When the bug only shows up at -O2, you debug -O2. A few flags make it kinder without changing the code the bug lives in.

FlagEffectCost
-g (-g2)line tables, variables, typesfile size
-g3also macro definitionslarger file
-fno-omit-frame-pointerkeeps rbp as a frame pointer, so unwinding is simpleone register, slightly slower
-fno-inlineno inlining, so every function is a real callvery different code, can hide the bug
-fno-inline-functionsstops heuristic inlining but honours inlinemilder change
-fno-ipa-sra, -fno-ipa-cpstops function cloning and argument rewritingleaves foo.constprop.0 names alone
-fno-tree-srakeeps small structs wholeslower
-fno-schedule-insns2stops late instruction reorderingremoves line-jumping

None is free, and any of them can make the bug vanish if it depended on the optimiser's exact decision, as a race or an uninitialised read often does. The honest procedure is to add one flag at a time and re-run the failing case after each, until you can see what you need. -fno-omit-frame-pointer is the one that rarely changes behaviour and often repairs broken backtraces, so start there.

Reading an optimised session

Several habits help when <optimized out> appears.

First, check whether the value is available a few instructions earlier or later. A location list covers ranges, so stepi once or twice can move you into one where the variable is live. info address VAR and info scope FUNCTION print the location expression and, for a list, say multi-location. info scope is the best summary of what DWARF can tell you about a function's variables.

Text
(gdb) info scope scale
Scope for scale:
Symbol x is multi-location:
  Range 0x1189-0x1195: a variable in $rdi
  Range 0x1195-0x119c: a complex DWARF expression:
     0: DW_OP_breg5 0 [$rdi]
     ...
Symbol k is constant 5
Symbol t is optimized out.

This sample is illustrative: ranges and registers depend on the compile. It shows the three cases: a multi-location value, a constant, and a variable the compiler removed entirely. A constant like k can be printed with print k even though it has no storage, because the debug info gives its value; if print says <optimized out> for something info scope calls constant, update GDB.

Second, treat the line column as approximate. At -O2, GDB's next follows the compiler's line table, which interleaves lines. The is_stmt flag in newer line tables marks the best place to stop for each line, and GDB 10 and later honours it, which already removes most of the backwards jumps. When the jumping is still too confusing, set step-mode on and stepi with x/i $pc give you the real order.

Third, take the backtrace from the unwinder, not from the registers. Inlined functions appear in bt as frames without their own return address, labelled by the inlined function's name, and up into them works. info frame marks an inlined frame, which says inlined into frame N.

Fourth, finish does not give a return value from an inlined call, since there is no return. Run till exit with a value for such a frame prints nothing useful, and the right move is next out of it.

When the symptom is a missing function

A breakpoint on a function the linker removed or the compiler specialised needs the clone's name. GCC names clones with suffixes such as .constprop.0, .isra.0, .part.0 and .cold. info functions scale lists matches including those suffixed names. A breakpoint on the plain name usually resolves all clones, as the earlier "2 locations" shows.

For the cleanest results, keep a separate debug-friendly build of the same source in your pipeline. Run it in CI at -Og, ship the -O2 build, and keep the -O2 debug symbols as a separate file keyed by build ID so a production crash can still be symbolised later.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.