温馨提示×

ubuntu c++如何远程调试

小樊
37
2026-08-28 12:28:08
栏目: 编程语言

在 Ubuntu 上远程调试 C++ 程序,常见做法有 GDB(命令行)+ gdbserverVS Code 远程调试。下面按常用程度给你一套完整说明。


一、使用 GDB + gdbserver(最通用、最稳定)

1️⃣ 环境说明

  • 开发机(本地):Ubuntu / Windows / macOS
  • 目标机(远程):Ubuntu(需要调试的程序运行在这里)

2️⃣ 安装必要工具

目标机(远程)

sudo apt update
sudo apt install gdb gdbserver

开发机(本地)

sudo apt install gdb

3️⃣ 编译程序(必须带调试信息)

g++ -g -O0 -o app main.cpp

⚠️ 注意:

  • -g:生成调试信息
  • -O0:关闭优化(否则变量可能被优化掉)

4️⃣ 在目标机上启动 gdbserver

方式一:启动新程序

gdbserver :1234 ./app

方式二:附加到已运行进程

gdbserver :1234 --attach <pid>

1234 是端口号,可自定义。


5️⃣ 在开发机上连接远程 gdb

gdb ./app

进入 gdb 后执行:

target remote 目标机IP:1234

例如:

target remote 192.168.1.100:1234

✅ 之后就可以使用标准 gdb 命令调试:

b main
c
n
s
p var
bt

6️⃣ 常见问题

程序崩溃在远程,如何调试?

gdbserver :1234 --attach <pid>

断点不生效?

  • 检查是否加 -g
  • 是否被优化(-O2

防火墙问题

sudo ufw allow 1234

二、使用 VS Code 远程调试(推荐)

1️⃣ 安装插件

  • Remote - SSH
  • C/C++

2️⃣ SSH 连接到远程 Ubuntu

Remote Explorer → SSH → 连接远程主机

3️⃣ 配置调试(launch.json)

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Remote Debug",
      "type": "cppdbg",
      "request": "launch",
      "program": "/home/user/app",
      "args": [],
      "stopAtEntry": true,
      "cwd": "/home/user",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "setupCommands": [
        {
          "description": "Enable pretty-printing",
          "text": "-enable-pretty-printing"
        }
      ],
      "pipeTransport": {
        "debuggerPath": "/usr/bin/gdb",
        "pipeProgram": "ssh",
        "pipeArgs": ["user@192.168.1.100"],
        "pipeCwd": "${workspaceFolder}"
      },
      "sourceFileMap": {
        "/home/user": "${workspaceFolder}"
      }
    }
  ]
}

点击 Run → Start Debugging 即可。


三、对比总结

方式 适合场景 易用性
gdb + gdbserver 服务器/嵌入式 ⭐⭐⭐
VS Code Remote 日常开发 ⭐⭐⭐⭐⭐
CLion Remote JetBrains 用户 ⭐⭐⭐⭐

四、常见错误速查

错误 原因
No symbol table info 没加 -g
Connection refused gdbserver 没启动 / 防火墙
断点不命中 优化级别过高

如果你愿意,可以告诉我:

  • ✅ 远程是 服务器 / 嵌入式 / Docker
  • ✅ 用的是 gdb / VS Code / CLion
  • ✅ 程序是 新的 / 已运行

我可以给你 完全针对你环境的配置示例

0