Using LLDB

Written on November 16, 2023

Using LLDB to debug C++ code


Using lldb is quite pleasant. It is a command line debugger that is available on MacOS and Linux. It is similar to gdb and I heared gdb is nicer. But on macos it's available by default so we'll use this only. It is also possible to use lldb on Windows but I have not tried it.

Installation

On MacOS, lldb is installed by default. On Linux, you can install it using the following command:

sudo apt install lldb

Usage

To debug a program, you can use the following command:

lldb <program>

This will open the lldb prompt. You can then use the following commands to debug your program:

  • run: Run the program
  • b <line_num>: Set a breakpoint at the specified line
  • b <function_name>: Set a breakpoint at the specified function
  • b 0x<address>: Set a breakpoint at the specified address
  • b: List all breakpoints

There is also a gui mode that can be used by running the following command:

lldb <program>
b <function_name>
run
gui

Example

Let's say we have the following program:

#include <iostream>

int main() {
    int a = 1;
    int b = 2;
    int c = a + b;
    std::cout << c << std::endl;
    return 0;
}

Then make sure you complie it with the -g flag:

g++ -std=c++11 -g main.cpp

We can debug it using the following commands:

lldb a.out
b 5
run

This will set a breakpoint at line 5 and run the program. The program will stop at line 5 and we can use the following commands to inspect the variables:

  • p a: Print the value of a
  • p b: Print the value of b
  • p c: Print the value of c
  • n: Execute the next line
  • s: Step into the next function call
  • bt: Print the stack trace
  • l: List the source code around the current line
  • c: Continue execution until the next breakpoint
  • q: Quit the debugger

References