Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining gdb print function for C structures

Tags:

c

emacs

gdb

when I write code in Java, I use the debugger embedded in Eclipse. When visualizing an object in this context, the debugger automatically calls the toString() function, feature that I find very convenient for quick visualization while exploring program state.

Now, when I work in C, I use emacs+gdb for debugging, but I didn't manage to find/recreate an equivalent feature for visualizing complicated C structures (i.e. call a specific printing function). Of course there is no general toString() method, but anyway I very often have implemented somewhere a printing function for my structures.

But when I want to visualize something in gdb, I have to call these printing functions manually from gdb doing p my_print_function(my_struct_pointer), which is quite inefficient (have to remember its name, type it correctly, moreover the standard output may be in another windows...).

The thing I'd like is to configure gdb to say "when calling gdb print function on the struct pointer type T, call automatically that user-defined printing function f...". Is there a way to do this ? Thanks in advance.

like image 775
Hobbes Avatar asked Mar 01 '13 11:03

Hobbes


2 Answers

use print struct_var to print members of a given struct

use print *struct_ptr to print members of a given struct pointer

use set print pretty on if you want gdb to print structures in an indented format with one member per line, like this:

$1 = {
        next = 0x0,
        flags = {
          sweet = 1,
          sour = 1
        },
        meat = 0x54 "Pork"
      }

and also you can use ptype struct_var to print out the definition of a given struct

more info here

like image 54
swpd Avatar answered Oct 18 '22 19:10

swpd


Good question.

Yes, kind of I guess. It seems GDB 7 has support for "pretty-printers" written in Python. Not as convenient (in my opinion) as using the already-written code in the actual target language, but perhaps good enough.

These are the commands for working with pretty-printers.

like image 39
unwind Avatar answered Oct 18 '22 18:10

unwind