VSCode 配置 ROS2 Launch 调试环境(Attach 方式)
- [1. 安装ROS2插件](#1. 安装ROS2插件)
- [2. 创建.vscode配置文件](#2. 创建.vscode配置文件)
- [3. 编译](#3. 编译)
- [4. 运行](#4. 运行)
- 问题1:launch.json,settings.json,tasks.json的区别是什么?
适用环境:
Ubuntu + ROS2 Foxy + colcon + VSCode + C++(rclcpp)
推荐方式:使用
ros2 launch启动整个系统,再 attach 调试单个节点
1. 安装ROS2插件

2. 创建.vscode配置文件
launch.json
bash
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to search_manager",
"type": "cppdbg",
"request": "attach",
"program": "${workspaceFolder}/install/test_node/lib/test_node/test_node",
"processId": "${command:pickProcess}",
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
settings.json
bash
{
"ROS2.distro": "foxy",
"ROS2.rosSetupScript": "${workspaceFolder}/install/setup.bash",
"files.associations": {
"*.hpp": "cpp",
"*.h": "cpp",
"*.c": "cpp",
"*.cpp": "cpp"
}
}
tasks.json
bash
{
"version": "2.0.0",
"tasks": [
{
"label": "colcon build (Debug)",
"type": "shell",
"command": "/bin/bash",
"args": [
"-c",
"source /opt/ros/foxy/setup.bash && source ${workspaceFolder}/install/setup.bash && colcon build --cmake-args -DCMAKE_BUILD_TYPE=Debug --symlink-install"
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always"
},
"problemMatcher": []
}
]
}
3. 编译
在 VSCode 中执行快捷键Ctrl + Shift + B,选择colcon build (Debug)
4. 运行
- 终端启动 ROS2 Launch
⚠️ 必须在Linux终端启动,而不是 VSCode launch
bash
source /opt/ros/foxy/setup.bash
source install/setup.bash
ros2 launch test_node test.launch.py
-
打开源码设置断点
-
启动调试 : VScode终端按下
F5,选择需要调试的进程即可

问题1:launch.json,settings.json,tasks.json的区别是什么?
1. tasks.json ------ 负责编译
相当于在终端输入:
bash
source /opt/ros/foxy/setup.bash
colcon build --cmake-args -DCMAKE_BUILD_TYPE=Debug
| 问题 | 解决方式 |
|---|---|
| 每次手动敲 build 命令 | Ctrl+Shift+B 一键编译 |
| 忘记 Debug 编译 | 强制 Debug |
| 环境变量没加载 | 在 command 里 source |
2. launch.json ------ 负责调试器行为
- 使用 gdb
- 附加到某个运行中的进程
- 让断点生效
| 问题 | 解决方式 |
|---|---|
| 断点不生效 | Debug 模式 + gdb |
| 多节点系统不好直接启动 | 用 attach |
| launch 参数丢失 | 终端启动 + attach |
3. settings.json ------ 负责编辑器行为
- 指定 ROS2 发行版(foxy)
- 指定 setup.bash 路径
- 帮助 IntelliSense 识别头文件
- 控制 C++ 代码提示
| 问题 | 解决方式 |
|---|---|
| 找不到 rclcpp 头文件 | 设置 ROS2.distro |
| 代码红线但能编译 | 配置 include |
| 智能提示失效 | 指定 cmake provider |
4. 三者关系图
┌──────────────┐
│ settings.json│
│ (代码提示) │
└──────┬───────┘
│
▼
修改代码 ──→ Ctrl+Shift+B ──→ tasks.json ──→ colcon build
│
▼
终端 ros2 launch
│
▼
F5 ──→ launch.json ──→ gdb attach
5. 角色分工
| 文件 | 职责 | 是否必须 |
|---|---|---|
| tasks.json | 编译 | ✅ 必须 |
| launch.json | 调试 | ✅ 必须 |
| settings.json | 代码提示 | ⚠ 建议 |