
如果你像我一样更喜欢使用 GUI 而不是命令行来设置断点、单步调试代码以及在程序运行时检查值,那么您可以通过以下方法设置 VSCode 和 gdbserver 以在运行时在本地编辑和调试代码它在远程服务器上。
注意:我在本地使用 macOS Sierra,远程计算机运行 Ubuntu 14.04,但本指南适用于任何 Unix 系统。(对不起,Windows 用户)。
注意:要在远程计算机上运行的命令以 为前缀remote$,本地命令以 为前缀local$。
安装因系统而异。在 Debian/Ubuntu 上,您可以执行以下操作:
remote$ apt-get install gdbserver
我使用Linuxbrew将其安装到我的用户文件夹中:
remote$ brew install gdbserver
在 macOS Sierra 上,我使用Homebrew安装 gdb:
local$ brew install gdb --with-all-targets
注意:--with-all-targets选项很重要;如果没有它,您将无法在操作系统或体系结构与本地计算机不同的远程计算机上进行调试。
此时,您应该能够在远程计算机上运行 gdbserver 并从本地 gdb CLI 连接到它。我将使用ssh-L选项将本地端口 9091 连接转发到远程端口 9091:
- local$ ssh -L9091:localhost:9091 user@remote
- remote$ cd ./myproject/ && make
- remote$ gdbserver :9091 ./myprogram
(端口 9091 是任意的;使用您喜欢的任何端口号)
让该命令在终端窗口中运行;它会等到 gdb 连接后再运行./myprogram。
在本地计算机上的另一个终端窗口中,运行 gdb:
- 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)
然后连接到 gdbserver 实例:
- (gdb) target remote localhost:9091
- Remote debugging using localhost:9091
- ...
- (gdb)
要验证一切是否正常,您可以运行各种 gdb 命令,例如info sources,或使用 来设置断点break。使用continue来运行./myprogram.
VSCode 会阻止您运行 gdb,除非它已签名
您可能已经注意到,对于基本功能,本地计算机上的 gdb CLI 不需要提供有关程序或其源代码的任何信息,除了运行 gdbserver 的主机和端口之外。但您希望保持本地和远程项目目录同步有两个重要原因:
list)。"program"launch.json 中的字段)。我选择使用sshfs,因为它需要最少的服务器端设置,但您可以使用 NFS、rsync 或其他替代方案。
使用 sshfs,在本地挂载远程项目文件夹:
- local$ mkdir ./myproject
- local$ sshfs user@remote:myproject ./myproject
注意:在 macOS 上,您可以稍后使用 卸载该目录umount ./myproject。在 Linux 上,使用fusermount -u ./myproject.
./myproject/在 VSCode 中打开新安装的项目,然后打开.vscode/launch.json或创建它(如果不存在):
- {
- "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"
- }
- }
- ]
- }
此配置将使单击“C++ Launch”将运行类似于以下内容的 gdb:
- local$ gdb ./myprogram
- ...
- (gdb) target remote localhost:9091
理想情况下,您希望能够运行单个命令或单击单个按钮来编译和调试程序。
这可能可以通过VSCode 任务和preLaunchTasklaunch.json 中的选项来完成,但我无法使用这些任务组合一个简单的解决方案。
相反,我编写了一个快速而肮脏的 shell 脚本prepare_remote_debug.sh:
- # 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'"
这是您的新工作流程:
./prepare_remote_debug.sh在终端窗口中运行。您的程序的输出将出现在这里。