How to Make An Interactive Debugger for Rust

Nilesh Katuwal Feb 02, 2024
How to Make An Interactive Debugger for Rust

This article will show you how to make an interactive debugger for Rust. First, let’s see how we can make it step by step.

Use VS Code and CodeLLDB Extension to Execute Programs in Rust

VS Code and the CodeLLDB extension execute programs written in Rust. The steps to be followed for having an interactive debugger for Rust are below.

  • Install VS Code.
  • Search Rust extension or new Rust-analyzer within VS Code.
  • Install the available extension in VS Code.

    The extension file depends upon the operating system you are using.

    1. C/C++ (Windows)
    2. CodeLLDB (OS X / Linux)
  • Check for the prerequisites and set up CodeLLDB for the platform (further setup might not be needed for v1.6).
  • Search for the extension CodeLLDB within VS Code and install it.
  • The main menu item run is added by the LLDB Debugger, from where we can start debugging. We need to select the environment (the debugger): select LLDB if the debugger is started for the first time.
  • The launch.json file will be opened when LLDB is selected. If that file does not open, it should be under your PC’s .vscode folder.

The launch.json should look like this.

"version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceRoot}/target/debug/hello_there",
            "args": [],
            "cwd": "${workspaceRoot}/target/debug/",
            "sourceLanguages": ["rust"]
        }
    ]
}

But suppose we want to have generic things and compile only a binary that matches the cargo folder name. In that case, we can use ${workspaceRootFolderName} variable substitution for the program key, as displayed below.

{
 "version": "0.2.0",
 "configurations": [
	 {
		 "type": "lldb",
		 "request": "launch",
		 "name": "Debug",
		 "program": "${workspaceRoot}/target/debug/${workspaceRootFolderName}",
		 "args": [],
		 "cwd": "${workspaceRoot}/target/debug/",
		 "sourceLanguages": ["rust"]
	 }
 ]
}

Basic Rust Program

Now our interactive debugger is ready, and we can run a program in it.

// This is the main function
fn main() {
    // when the compiled binary is called statements are executed

    // Print text to the console
    println!("Hello, I'm using Rust.");
}

Output:

Hello, I'm using Rust.

Following all these steps properly, we can run and debug the Rust programs in VS Code. The installation of the extension and its configuration should be prioritized to ensure you can run the Rust program.