DEV Community

mahesh_attarde
mahesh_attarde

Posted on

[GDB-Quick] Prints – No Need to do "std::cout" and compile again

For debugging, most obvious way to start is adding print.
When we have gdb, we dont need that (implied software built is in debug mode).
Lets see alternate ways to do that in gdb.

Printing Variable at some line.

We have breakpoints at hand. when breakpoint hits we can print variable values required or message needed (like which if-else branch taken (-q), ¯_(ツ)/¯ ).

(gdb) break source.cpp:50  <enter>
(gdb) command <enter>
Type commands for breakpoint(s) 1, one per line.
End with a line saying just "end".
>print "hello World!" 
>end
Enter fullscreen mode Exit fullscreen mode

When breakpoint hits on source file source.cpp at line 50 It prints "hello World!". No need to edit code or recompile it!

On breakpoint, we specify series of commands that need to process. it can be made simple as printing single variable to printing complete data-structure.

Same can be done with dprintf breakpoint and print, however first one provides more flexible and easy to use formatting. I hate dprintf!

Print but more efficient

Our first command of use is

(gdb) print a
(gdb) p a
Enter fullscreen mode Exit fullscreen mode

This is fine, even if we have array.
At times we are interested in buffer contents irrespective of its data structure, treating it like memory area.

(gdb) print &a@10 
Enter fullscreen mode Exit fullscreen mode

Above command accepts address and 10 further locations from it. try a@10 and see how cool that feature becomes!

same with different formatting, printing 20('n'umber) 'f'ormat 'w'ords with address a

(gdb) x/20fw &a
Enter fullscreen mode Exit fullscreen mode

We also want to check same variable at different breakpoints

display <var_name>
Enter fullscreen mode Exit fullscreen mode

is easiest way than doing p everytime.

HTH, Happy Hacking!

Discussion (0)