Example code
struct List { struct Node { char val{}; Node* next{}; }; Node* first{}; Node* last{}; void add(char val) { Node* node = new Node; node->val = val; if (!first) { first = node; } if (last) { last->next = node; } last = node; } }; int main() { List list; list.add('A'); list.add('B'); list.add('C'); return 0; }
Without pretty printer
(gdb) b 29 (gdb) r Breakpoint 1, main () at main.cpp:29 29 return 0; (gdb) p list $1 = {first = 0x55555556b2b0, last = 0x55555556b2f0}
With pretty printer
import gdb class ListPrinter: def __init__(self, val): self.val = val def to_string(self): elements = [] node = self.val['first'] while node: char_val = chr(int(node['val'])) elements.append(f"{char_val}") node = node['next'] return "[ " + ", ".join(elements) + " ]" def register_printers(obj): if obj is None: obj = gdb obj.pretty_printers.append(lookup_printer) def lookup_printer(val): if str(val.type) == 'List': return ListPrinter(val) return None register_printers(None)
(gdb) source list_printer.py (gdb) b 29 (gdb) r Breakpoint 1, main () at main.cpp:29 29 return 0; (gdb) p list $1 = [ A, B, C ]