Harolinch's blog

By Harolinch, history, 6 years ago, In English

i used to use visual studio in debugging, but now i switched to linux and of course i need to learn to debug with gdb, may someone share his experience with me

  • Vote: I like it
  • +15
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
Rev. 2   Vote: I like it +1 Vote: I do not like it

The terminal interface of gdb is often cumbersome to use directly. It is recommended to use a windows-based GUI such as the linux version of the Code::Blocks IDE freeware that runs gdb internally for debugging, but is much more user-friendly.

»
6 years ago, # |
Rev. 2   Vote: I like it +15 Vote: I do not like it

GDB, by default, only prints one line of code at a time. This makes it very difficult to understand current state and context of the code. Printing more lines (l) is helpful, but also quite annoying. You can enable the TUI mode (tui enable, or C-x a), which opens a window with the current code, and highlights the current line.

To debug, it's handy to pass the input via from a text file: start <input_text_file.

Then use the common commands to debug: print a variable p x, create a breakpoint b, continue to the next breakpoint c, go to next line n, step to next executed line s, jump once to line u 123, finish a function and print return value fin, show the call stack with bt, ...

Notice, each one of these commands has dozens of options and different usages. E.g. you can make a breakpoint in the current line b, by specifying a line number b 123, by a function name b my_function, ... Just glance over the documentation of gdb, so that you know what is possible.

Some random tricks:

  • Hit enter to repeat the last command
  • C-r quickly find and paste a previous command
  • p /t x prints binary representation of variable x
  • At a breakpoint, command + p x + end. Now it will print x every time you hit the breakpoint.
  • You can record the program execution, and then go backwards.
  • To find the location of an error (e.g. index out of bound), just run the program, and after the crash just press up a few times (this goes up the call stack until you are at the error location).
  • Conditional breakpoints b if x > 10