Question

How to View Global and Local Variables in GDB

cvariablesgdbglobal-variables

Question

How can I print all global variables and local variables while debugging? Is this possible in GDB?

Short Answer

By the end of this page, you will understand how GDB shows local and global variables, which commands list them, and when those commands work. You will also learn the difference between variables currently in scope and variables merely known from debug symbols.

Concept

GDB can show variables, but global and local variables are handled differently.

  • Local variables belong to a specific function call frame.
  • Global variables exist for the whole program or translation unit.

In GDB, you usually inspect them with different commands:

  • info locals shows local variables in the current stack frame.
  • info variables lists global and static variables known from debug information.
  • print variable_name prints the value of a specific variable.
  • info args shows function arguments for the current frame.

This matters because debugging is often about answering two questions:

  1. What values does this function currently see? → locals and arguments
  2. What program-wide state exists? → globals and statics

A key detail is that GDB depends heavily on debug symbols. If the program was not compiled with debugging information, variable names and scopes may be missing or incomplete. In C and C++, this usually means compiling with something like:

gcc -g program.c -o program

or

g++ -g program.cpp -o program

Optimization can also affect what GDB can show. Highly optimized builds may remove variables, inline code, or keep values only in registers in ways that are hard to inspect reliably.

Mental Model

Think of debugging like inspecting a building:

  • Global variables are like items stored in the building lobby. They exist independently of any one room.
  • Local variables are like items inside the room you are currently standing in.
  • Stack frames are the rooms. Each function call creates a new room.

So if you want to see local variables, you first need to stand in the right room: the correct frame.

If you want to see globals, you ask for the building-wide inventory.

Take Quiz

Syntax and Examples

The most common GDB commands for this topic are:

info locals
info args
info variables
print variable_name
frame 0
backtrace

Example C program

#include <stdio.h>

int global_count = 42;
static int file_only_flag = 1;

void greet(const char *name) {
    int local_length = 5;
    printf("Hello %s\n", name);
    printf("%d\n", local_length);
}

int main(void) {
    int local_main = 10;
    greet("Ada");
    printf("%d %d\n", global_count, local_main);
    return 0;
}

Compile with debug symbols:

gcc -g example.c -o example

Start GDB:

gdb ./example

Set a breakpoint and run:

break greet
run

Now you can inspect function state:

info args
info locals

Possible output:

(gdb) info args
name = 0x555555558004 "Ada"

(gdb) info locals
local_length = 5

To inspect a specific global:

print global_count

To list global and static variables known to GDB:

info variables

You can also filter the result:

info variables global_count

Step by Step Execution

Use this small example:

#include <stdio.h>

int counter = 100;

void work(int step) {
    int total = step + 1;
    printf("total=%d\n", total);
}

int main(void) {
    work(3);
    return 0;
}

Compile and debug:

gcc -g demo.c -o demo
gdb ./demo

Set a breakpoint inside work:

break work
run

When execution stops, GDB is paused in the work frame.

What happens now?

  1. counter already exists because it is global.
  2. step is the function argument for the current call.
  3. total is the local variable created inside work.

Run these commands:

info args
info locals
print counter

Expected reasoning:

  • info args shows step = 3
  • info locals shows total = 4
  • print counter shows 100

If you move to another frame, the visible locals change.

For example:

backtrace
frame 1
info locals

If frame 1 is main, then total is no longer in scope because it belongs to work, not main.

That is the key rule: locals depend on the current frame; globals do not.

Real World Use Cases

Developers use these commands in many practical debugging situations:

  • Investigating crashes: inspect local state in the function where the crash happened.
  • Checking configuration state: print global flags or static settings that affect program behavior.
  • Debugging wrong calculations: inspect local intermediate values step by step.
  • Tracing request handling in server code: view function arguments and locals for the current request.
  • Embedded or systems debugging: inspect global status variables and current function state.
  • Legacy code debugging: use info variables to discover what global/static state exists before changing code.

For example, if a parser fails, you may inspect:

  • local token values in the current function
  • global error counters
  • static cached state in the file
Take Quiz

Real Codebase Usage

In real projects, developers rarely print every variable all the time. Instead, they use these commands strategically.

Common patterns

  • Guard investigation: stop at a failing condition and inspect info locals.
  • Argument validation: use info args to check whether bad input entered the function.
  • Shared-state debugging: use print on globals or statics that influence many functions.
  • Frame navigation: use backtrace and frame N to inspect locals at different call levels.
  • Targeted lookup: use info variables regex to search for globals by name.

Typical workflow

break some_function
run
info args
info locals
print global_config
backtrace
frame 1
info locals

Why targeted inspection is better

Large codebases may contain hundreds or thousands of globals and statics. info variables can produce a lot of output, so developers often:

  • search by variable name
  • inspect one module at a time
  • print specific values instead of everything

This keeps debugging focused and faster.

Common Mistakes

1. Expecting info variables to show current values of all globals

info variables mainly lists variables known from debug symbols. It does not behave like info locals for the current frame.

You often still need:

print some_global

2. Running info locals in the wrong frame

Broken expectation:

backtrace
frame 1
info locals

If you wanted variables from another function, you must select that function's frame first.

3. Compiling without debug symbols

Broken build:

gcc program.c -o program

Better:

gcc -g program.c -o program

Without -g, GDB may not know local variable names.

4. Using heavy optimization while learning to debug

This can make variables appear missing or strange.

Prefer:

gcc -g -O0 program.c -o program

5. Confusing local, global, and static variables

  • local: inside a function
  • global: declared outside functions
  • static file-scope variable: outside a function, but limited to one source file
  • static local variable: inside a function, but persists between calls

6. Assuming out-of-scope locals still exist

Broken assumption:

frame main
print total

If total was local to work, this will fail because it is not visible in main.

Comparisons

CommandWhat it showsScope-sensitive?Typical use
info localsLocal variables in current frameYesInspect current function state
info argsFunction arguments in current frameYesCheck inputs to current function
print xValue of a specific expression or variableYes, unless global is fully accessibleInspect one value
info variablesGlobal and static variables from debug infoNo frame neededDiscover available globals/statics
backtraceCall stackNot about variables directlyFind the right frame
frame NSelect stack frameYesChange which locals are visible

info locals vs info variables

  • info locals is about current execution context.
  • info variables is about known symbols in the program.

print vs listing commands

  • Use print when you know exactly what you want.
  • Use info locals or info variables when you are exploring.
Take Quiz

Cheat Sheet

# Show local variables in current function
info locals

# Show function arguments in current function
info args

# Show global/static variables known from debug info
info variables

# Search globals/statics by name
info variables NAME

# Print one variable or expression
print variable_name
print some_struct.field
print array[0]

# See call stack
backtrace

# Switch to a different frame
frame 0
frame 1

Best compile options for debugging

gcc -g -O0 file.c -o file

Rules to remember

  • Locals belong to the current frame.
  • Globals can usually be printed from anywhere.
  • info variables lists symbols; it is not the same as printing all live values.
  • Missing debug info means poor variable visibility.
  • Optimization may hide or rearrange variables.

FAQ

Can GDB print all local variables at once?

Yes. Use:

info locals

This shows locals for the currently selected stack frame.

Can GDB print all global variables at once?

GDB can list global and static variables with:

info variables

Then you can print individual ones using print name.

Why does info locals show nothing?

Possible reasons:

  • you are in the wrong frame
  • the function has no local variables
  • the program was built without -g
  • optimization removed or hid variables

What is the difference between info args and info locals?

  • info args shows function parameters
  • info locals shows local variables inside the function body

Do I need to stop at a breakpoint first?

Usually yes. GDB must pause the program so it can inspect the current frame and variable state.

Does info variables include static variables?

Yes, it typically lists global and static variables known from debug information.

Why can I print a global from another function but not a local?

Because globals exist outside any single function frame, while locals only exist within their own function scope.

Take Quiz

Mini Project

Description

Create and debug a small C program that uses both global and local variables. This project demonstrates how GDB treats program-wide state differently from function-specific state and helps you practice the most useful inspection commands.

Goal

Use GDB to inspect locals, arguments, and globals in the correct stack frame.

Requirements

  • Write a C program with at least one global variable and one function with local variables.
  • Compile the program with debug symbols enabled.
  • Set a breakpoint inside the function.
  • Use GDB to display arguments, locals, and a global variable.
  • Move between stack frames and observe how local visibility changes.
Take Quiz

Keep learning

Related questions

View more