如何使用vscode远程debug c++代码

最近c++的编码需求又来了一些,需要进行debug,之前都是打日志来debug,着实非常不方便,查了一下资料,最终配置了vscode的远程debug环境。

我的环境:

  • 客户端:win11 + vscode
  • 服务端:ubuntu 20.04+gdb,服务端是一个cmake项目,启动即一个可执行文件

环境初始化(vscode的插件、ubuntu的gdbserver)主要参考这篇文章,具体细节不再赘述:VsCode + gdb + gdbserver远程调试C++程序

Debug流程

  1. 启动gdbserver
    执行以下命令

    1
    gdbserver 192.168.1.123:2000 ./bin/testapp.out hello

    重要:你的程序启动参数,需要在gdbserver启动时指定,而不是在launch.json里指定!

  2. 配置vscode
    使用下面的配置文件进行配置

    1. launch.json
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      {
      // 使用 IntelliSense 了解相关属性。
      // 悬停以查看现有属性的描述。
      // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
      "version": "0.2.0",
      "configurations": [
      {
      "name": "g++ - 生成和调试活动文件",
      "type": "cppdbg",
      "request": "launch",
      "program": "./bin/testapp.out", //这里是你的可执行文件地址
      "stopAtEntry": false,
      "cwd": "/home/dev/", //这里是执行debug时你的当前目录
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "setupCommands": [
      {
      "description": "为 gdb 启用整齐打印",
      "text": "-enable-pretty-printing",
      "ignoreFailures": true
      },
      {
      "description": "将反汇编风格设置为 Intel",
      "text": "-gdb-set disassembly-flavor intel",
      "ignoreFailures": true
      },
      {
      "description": "Test", //这里指定后可以查看gdb的数组、向量等容器的内容,比较方便
      "text": "python import sys;sys.path.insert(0, '/usr/share/gcc/python');from libstdcxx.v6.printers import register_libstdcxx_printers;register_libstdcxx_printers(None)",
      "ignoreFailures": false
      }
      ],
      "preLaunchTask": "C/C++: g++ 生成活动文件",
      "miDebuggerPath": "/usr/bin/gdb",
      "miDebuggerServerAddress":"192.168.1.123:2000" //这里修改为你的服务器ip
      }
      ]
      }
    2. tasks.json
      1
      2
      3
      4
      5
      6
      7
      8
      {
      // See https://go.microsoft.com/fwlink/?LinkId=733558
      // for the documentation about the tasks.json format
      "version": "2.0.0",
      "tasks": [

      ]
      }

然后就可以愉快的debug啦!
在vscode 中按f5,就会启动debug进入你的代码,f10逐步调试,f11进入函数,f9执行到下一个断点

遇到的坑

  1. 参数老是传不进去,以为是哪里有问题,最后发现参数是要在gdbserver启动时指定
  2. 在Vscode中按f5启动调试时,提示找不到g++/c++,可以无视错误继续试试

参考

如何使用vscode远程debug c++代码

http://example.com/2024/11/09/vscode-remote-debug-cplus/

作者

简单代码

发布于

2024-11-09

更新于

2025-10-12

许可协议