Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use gdb to debug your code?

Tags:

debugging

gdb

As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?

like image 900
Matthew Avatar asked Sep 26 '08 15:09

Matthew


People also ask

How do I run a GDB code?

Run the code by typing “run or r”. If you haven't set any breakpoints, run command will simply execute the full program. 11.

How does GDB debugger works?

How GDB Debugs? GDB allows you to do things like run the program up to a certain point then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line. GDB uses a simple command line interface.

What is GDB debugging tool?

GDB stands for the “Gnu DeBugger.” This is a powerful source-level debugging package that lets you see what is going on inside your program. You can step through the code, set breakpoints, examine and change variables, and so on. Like most Linux tools, GDB itself is command line driven, making it rather tedious to use.


1 Answers

Some hints:

  • use a graphical frontend (kdbg is quite good, ddd is at least better than command-line gdb, kdevelop has a nice gdb frontend but has some bgs, nemiver looks quite nice as well but is still in the works)
  • make sure to have debug symbols and source code for all important parts (your own code and also some system libs)
    • on RedHat, you can install the -debuginfo packages to make both symbols and source code magically appear in the debugger - really cool because you can looks into libc function calls etc.
    • on Debian/Ubuntu, you can install the -dbg packages to get symbols; installing appropriate source files for system packages seems to be difficult, though
  • I tend to add assert() and abort() calls in places that should not be reached, or in places that I want to study (some kind of heavy-weight breakpoint)
  • ideally the assert() or abort() calls should be wrapped in some method or macro that only enables them in Debug releases, or even better that only enables them if a certain env var is set
  • install a signal handler for SIGSEGV and SIGABRT; personally I check if a certain env var is set before installing the handlers; and in the handler I execute a hardcoded external command which usually lives somewhere in ~/.local/bin/; that command might then start kdbg and attach it to the crashing app. Voila, debugger pops up the moment your app does something bad.
  • If you use unit tests, you could similarly attach a debugger whenever a test case fails, to inspect the app then.
like image 196
oliver Avatar answered Oct 15 '22 16:10

oliver