Printing Variables in GDB - StevenLwcz/gdb-python GitHub Wiki

There are many ways to print variables in GDB.

Manually

{gdb) print variable
{gdb) print /FMT variable
(gdb) printf format-string variable

See the inbuilt documentation for more information.

(gdb) help print
(gdb) help printf
(gdb) help data  

Help for /FMT is here.

(gdb) help x

Automatically

Display a Variable After Each Step

(gdb) display variable-1
(gdb) display variable-2

(gdb) help display

Using Breakpoint Hooks

The (gdb) command allows you to execute any set of GDB commands once a break point has been hit. [num] is the gdb breakpoint number it allocates when a breakpoint is set.

(gdb) command [num]
(gdb) print variable
(gdb) end

(gdb) help command

Display all break point information:

(gdb) info break

After a Specified Gdb Command Has Been Executed

(gdb) define hook-[gdb-command]

For example after each step (similar to display but you can add other gdb commands).

(gdb) define hook-step
(gdb) print /x variable
(gdb) printf format-string variable
(gdb) info locals
(gdb) end

(gdb) help define

Info Commands

Print out groups of variables.

(gdb) info locals
(gdb) info args
(gdb) info variables

(gdb) help info
(gdb) help info variables

Python Scripts

(gdb) info locals displays the current block and all parent blocks. If you want a bit of finesse.

Current block

block.py

frame = gdb.selected_frame()
block = frame.block()
for symbol in block:
    if symbol.is_variable:
        var = frame.read_var(symbol)
        print(str(symbol.type), symbol.name, var)

(gdb) so block.py

Static variables

(gdb) info variables displays all static items more than just in the program. If you just want the ones in your program:

frame = gdb.selected_frame()
block = frame.block().static_block
for symbol in block:
    if symbol.is_variable:
        var = frame.read_var(symbol)
        print(str(symbol.type), symbol.name, var)

(gdb) so static.py

Global Variables

Ditto with globals.

frame = gdb.selected_frame()
block = frame.block().global_block
for symbol in block:
    if symbol.is_variable:
        var = frame.read_var(symbol)
        print(str(symbol.type), symbol.name, var)

(gdb) so global.py

Docs

Check out the Gdb documentation for more information.