Courses



GDB Tutorial


Introduction

GDB, or the GNU Debugger, is a powerful tool for debugging programs written in C and other languages. It allows you to inspect and manipulate the execution of a program, making it an essential tool for software developers.

Installation

Ensure that GDB is installed on your system. You can install it using the package manager on Linux or download it from the official GDB website.

# Example installation on Ubuntu
sudo apt-get install gdb

Basic Commands

  1. Starting GDB:
    To debug a program, compile it with debugging symbols and start GDB: gcc -g -o my_program my_program.c
    gdb ./my_program
  2. Setting Breakpoints:
    Set breakpoints at specific lines to pause execution and inspect the program's state: break main
  3. Running the Program:
    Start or continue the program's execution: run
  4. Printing Variables:
    Inspect variable values during program execution: print my_variable
  5. Stepping Through Code:
    Execute the program one line at a time: next

Example Program

Consider the following C program (example.c):

#include <stdio.h>

int main() {
    int x = 5;
    int y = 10;
    int sum = x + y;

    printf("Sum: %d\n", sum);

    return 0;
}

1. Compile the program with debugging symbols: gcc -g -o example example.c

2. Start GDB and set a breakpoint: gdb ./example
break main

3. Run the program: run

4. Print variable values and step through the code: print x
print y
next

Conclusion


Copyright © BHH. All Rights Reserved                 |   CSE  |  IIITS