>

Debugging Rust code

Debugger (LLDB and GDB)

Basically there are 2 debuggers to choose from: LLDB and GDB.

  • LLDB is part of LLVM, which is a set of compiler tools,
  • and GDB is part of the GNU project.

If command line is your flavor, you can use rust-gdb. If you use a IDE like VSCode, LLDB is an easy choice.

Setup GDB on the command line

Rust comes with a command line tool called rust-gdb, which is described here.

Install it on Arch Linux: $ sudo pacman -S gdb

If you are on an ARM based machine (like Apple computers with an (Apple) M1 chip and upwards), you are out of luck. GDB is not supported, and you have to use the LLDB, which is the default debugger on MacOS.

Then you can use the command line tool to set break points and start the debugging process. For e.g., I navigate to one of my projects and do these basic commands below:

cargo build    # A
rust-gdb target/debug/NAME_OF_YOUR_BINARY_FILE      # B

(gdb) b main:5   # C
(gdb) r          # D
...
(gdb) p my_var   # E

Explanation:

  • A: Build the project
  • B: Start the debugger
  • C: “b” Set a break point at line 5 in the main function
  • D: “r” Run the program until the 1st break point is reached
  • E: “p” Print the value of the variable my_var

If you like a more visual experience, go to next section, which has a debugger interface built into.

Setup LLDB in VSCode

  • Using “Extensions” menu on the left sidebar of VSCode, search & install an extension called “CodeLLDB”.

  • After its ready, you feel free to set any break points in your code, and start debugging.

  • when starting the debugger via the UI, it will stop right the breadkpoints you set before that, then you can inspect the variables and the current stack of your code.

  • NOTES: need to specify in launch.json file of vscode so that making using LLDB instead of GDB like we did via the command line. LLDB is well supported within VSCode.

hnidoaht-101

A 🦀 love open sources. Actually just a pet lover with passion to build the nice things.


By hn1Do@ht-0n3z3Roo11e, 2022-09-22