Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using gdb - Comprehensive Tutorial

Introduction

gdb (GNU Debugger) is a powerful debugging tool for C (and C++) programs. It allows you to see what is going on inside your program while it runs or what your program was doing at the moment it crashed. This tutorial will guide you through the basics and advanced techniques of using gdb.

Setting Up gdb

Before you can use gdb, you need to install it. On most Linux distributions, you can install gdb using the package manager:

sudo apt-get install gdb

Once installed, you can check the version of gdb by running:

gdb --version

Compiling Your Program with Debug Information

To use gdb effectively, you need to compile your C program with debugging information. This is done by adding the -g flag to the gcc compiler:

gcc -g -o myprogram myprogram.c

Starting gdb

To start gdb, simply run:

gdb myprogram

This will load your program into gdb, but it will not start running it yet.

Running Your Program

To start running your program inside gdb, use the run command:

run

If your program requires command-line arguments, you can specify them after the run command:

run arg1 arg2

Setting Breakpoints

Breakpoints allow you to stop your program at a specific line of code so you can inspect its state. To set a breakpoint, use the break command followed by the line number or function name:

break main

break myprogram.c:10

Inspecting Variables

Once your program is stopped at a breakpoint, you can inspect the values of variables using the print command:

print variable_name

To inspect all local variables, use the info locals command:

info locals

Stepping Through Code

To execute your program one line at a time, use the step command. This will step into functions. If you want to step over functions, use the next command:

step

next

Continuing Execution

After hitting a breakpoint or stepping through code, you can continue running your program until the next breakpoint or the end of the program using the continue command:

continue

Examining the Call Stack

If your program crashes, you can examine the call stack to see the sequence of function calls that led to the crash. Use the backtrace command to view the call stack:

backtrace

Exiting gdb

To exit gdb, use the quit command:

quit

Conclusion

gdb is a powerful tool that can help you find and fix bugs in your C programs. This tutorial covered the basics of using gdb, including setting breakpoints, inspecting variables, stepping through code, and examining the call stack. With practice, you'll become more proficient in using gdb and be able to debug your programs more effectively.