Debugging C/C++ Programs Remotely Using Visual Studio Code and gdbserver

1. Install gdbserver on the remote machine

remote$ apt-get install gdbserver
remote$ brew install gdbserver

2. Install gdb on your local machine

local$ brew install gdb --with-all-targets

3. Test gdb

local$ ssh -L9091:localhost:9091 user@remote
remote$ cd ./myproject/ && make
remote$ gdbserver :9091 ./myprogram
local$ gdb
GNU gdb (GDB) 7.12
Copyright (C) 2016 Free Software Foundation, Inc.
...
For help, type "help".
Type "apropos word" to search for commands related to "word".
(gdb)
(gdb) target remote localhost:9091
Remote debugging using localhost:9091
...
(gdb)

4. codesign gdb

5. Synchronize local and remote file systems

  • Viewing source code in the gdb CLI (i.e. list).
  • The VSCode C/C++ extension requires you to provide the path to the compiled executable to launch gdb. (The "program" field in launch.json).
local$ mkdir ./myproject
local$ sshfs user@remote:myproject ./myproject

6. Configure Visual Studio Code

{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/myprogram",
"miDebuggerServerAddress": "localhost:9091",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "gdb"
},
"windows": {
"MIMode": "gdb"
}
}
]
}
local$ gdb ./myprogram
...
(gdb) target remote localhost:9091

7. Write a script to compile your program and launch gdbserver

# Kill gdbserver if it's running
ssh user@remote killall gdbserver &> /dev/null
# Compile myprogram and launch gdbserver, listening on port 9091
ssh \
-L9091:localhost:9091 \
user@remote \
"zsh -l -c 'cd myproject && make && gdbserver :9091 ./myprogram'"

8. Start debugging

  1. Edit some code.
  2. Run ./prepare_remote_debug.sh in a terminal window. Your program’s output will appear here.
  3. Set some breakpoints.
  4. Run “C++ Launch”.
  5. Step through your code in VSCode’s debugger.
  6. Repeat.

--

--

--

Developer @ Microsoft, OneDrive Web

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Spencer Elliott

Spencer Elliott

Developer @ Microsoft, OneDrive Web

More from Medium

How to enable Linter in Visual Studio Code — Python

Comparison Between PyCharm VSCode

Install WSL 2 + Ubuntu 20.04 LTS on Windows 10 and open Visual Studio Code from the terminal

Sorting Algorithms in Python — Quicksort worst-case, randomized version and three-way