How to debug Rust CLI application with VsCode using Windows<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to debug Rust CLI application with VsCode using Windows

Posted on: November 21, 2022

Prerequisites

Before debugging using Visual Studio Code (VSCode), you need to have VsCode and CodeLLDB extension.

Launch File

VsCode's debug configuration file is under .vscode/launch.json. You need two entries: one for your executable (command line) to test the cli and one for the unit tests.

1{
2 "version": "0.2.0",
3 "configurations": [
4 {
5 "type": "lldb",
6 "request": "launch",
7 "name": "Debug executable 'rust-p2p-chat'",
8 "cargo": {
9 "args": ["build", "--bin=rust-p2p-chat", "--package=rust-p2p-chat"],
10 "filter": {
11 "name": "rust-p2p-chat",
12 "kind": "bin"
13 }
14 },
15 "args": [
16 "--ip",
17 "127.0.0.1",
18 "--port",
19 "8077",
20 "--username",
21 "YourNameHere"
22 ],
23 "cwd": "${workspaceFolder}"
24 },
25 {
26 "type": "lldb",
27 "request": "launch",
28 "name": "Debug unit tests in executable 'rust-p2p-chat'",
29 "cargo": {
30 "args": [
31 "test",
32 "--no-run",
33 "--bin=rust-p2p-chat",
34 "--package=rust-p2p-chat"
35 ],
36 "filter": {
37 "name": "rust-p2p-chat",
38 "kind": "bin"
39 }
40 },
41 "args": [],
42 "cwd": "${workspaceFolder}"
43 }
44 ]
45}

One detail that is not obvious is how to have default arguments for your executable. The configuration has a args property that allows an array of arguments. Each element of the array must be what you would separate by a space. For example, if you type normally myApp.exe --argument1 value1, then in the args, you write:

1"args": [
2 "--argument1",
3 "value1",
4]

Of course, all the rust-p2p-chat needs to change for your application name. The good news is that if your project does not have any launch.json file, you can have VsCode generates the scaffolding for you. Then, only the args is needed to fill.

How to debug?

The last step is to set a breakpoint. Click on the left side gutter of the editor next to the line number. A red dot appears, then you can launch the application using the VsCode Run and Debug using the configuration to debug the executable. The editor will stop once the program reaches the line with the breakpoint.