Course contentsShow
← C
Lesson 1161 of 1,21916. Practice and ProjectsFree lesson

Starting a program in `gdb` or `lldb`

Starting a program in gdb or lldb

What you'll learn: How to launch your compiled C program inside a debugger to gain total control over its execution.

The Pilot’s Cockpit

Think of running your program normally like watching a plane fly from the ground. You see it move, and you see it crash, but you don’t know why. Running your program in a debugger (gdb for Linux or lldb for macOS) is like sitting in the cockpit. You have your hand on the throttle, you can see every dial, and you can tell the plane exactly when to stop mid-air so you can look around.

The Debugging Flag

Before the debugger can help you, you must compile your code with "debug symbols." This tells the compiler to save information about which line of code corresponds to which machine instruction. You do this by adding the -g flag:

// Save this as hello.c
#include <stdio.h>

int main() {
    printf("Ready for takeoff!\n");
    return 0;
}

Compile it like this: gcc -g hello.c -o hello

Ignition: Loading and Running

To start, you don't run the program directly. Instead, you run the debugger and tell it which file to "load." Open your terminal and type:

  • For gdb: gdb ./hello
  • For lldb: lldb ./hello

You are now inside the debugger's own command environment. The program hasn't actually started yet; it’s sitting on the runway. To make it go, type the command run (or just r) and hit Enter.

The debugger will execute the program. If everything is fine, it will finish normally. However, if the program crashes, the debugger will "catch" it at the exact moment of failure, freezing time so you can inspect what went wrong. When you are finished, type quit to exit the debugger.

Why this matters

Starting a program this way allows you to set "breakpoints" (stop signs) later on. By launching through gdb or lldb, you shift from being a passive observer to an active investigator. You aren't just guessing why your code failed; you are watching it happen in slow motion.

Key takeaway

Compile with the -g flag, then use the run command inside gdb or lldb to execute your program under professional supervision.