Блог пользователя Harolinch

Автор Harolinch, история, 6 лет назад, По-английски

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

  • Проголосовать: нравится
  • +15
  • Проголосовать: не нравится

»
6 лет назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

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 лет назад, # |
Rev. 2   Проголосовать: нравится +15 Проголосовать: не нравится

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