GDB the debugger for C

13-03-2022

Why use a debugger

Debuggers are the best way for a programmer to find bugs. Print statements have been the first only way for most of us to debug our programs. However they are not as efficient as a debugger. With a debugger you can see the code executing live, you can inspect the value of variables, see which function called what, you can change values of variables on the fly and much more. Especially with C, where segmentation faults are not uncommon and where printf statements sometimes become useless, gdb is a must.

Basic commands

Using gdb

First for gdb to be able to debug your c program you'll need to compile it with the -g or -ggdb flag which generates debugging symbols. Sometimes you might need to reduce the optimization from -O3 to -O0 so that code is less optimized but easier to debug otherwise some values might be optimized out. To run gdb run gdb ./my-program. You can also use the --tui flag which will also display your code at the same time.