在 VSCode 中调试使用 CMake 编译的程序,按照以下步骤进行:
1. **安装必要的扩展:**
- 打开 VSCode,并确保你已经安装了以下扩展:
- C/C++(由 Microsoft 提供)
- CMake
- CMake Tools
2. **配置 CMake:**
- 确保你的项目有一个 `CMakeLists.txt` 文件,并且能够通过 cmake 命令生成构建文件。
3. **设置 CMake 构建目录:**
- 通常你需要创建一个单独的构建目录,例如 `build`,来存放编译生成的文件。
4. **配置 CMake Tools:**
- 打开命令面板(Ctrl+Shift+P)并选择 `CMake: Configure`。选择一个合适的 CMake 配置选项,例如 `GCC`、`Clang` 或其它适合你的编译器。
- 根据项目需求,可以调整 `CMake Tools` 设置,例如设置构建目录,打开项目根目录中的 `CMakeLists.txt` 文件,CMake Tools 会自动检测并提示配置。
5. **生成默认的 `tasks.json` 和 `launch.json` 文件:**
- 需要创建这两个重要的配置文件,它们告诉 VSCode 如何构建和调试你的项目。
- 在项目根目录下的新建 `.vscode` 目录,然后在该目录中创建 `tasks.json` 和 `launch.json` 文件。
**tasks.json:**
```json
{
"version": "2.0.0",
"tasks": [
{
"label": "CMake Build",
"type": "shell",
"command": "cmake",
"args": [
"--build",
"${workspaceFolder}/build"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "Generated by CMake."
}
]
}
```
**launch.json:**
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/<your_executable>",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "CMake Build",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}
```
- 请将 `<your_executable>` 替换为你的可执行文件的名称。
6. **构建项目:**
- 通过 VSCode 中的任务运行器或命令面板(Ctrl+Shift+P)选择 `Tasks: Run Build Task`,选择并运行 `CMake Build` 任务。这会根据配置运行 CMake,并在指定的构建目录中生成可执行文件。
7. **调试项目:**
- 打开调试面板(侧边栏上的虫子图标,或使用快捷键 F5),选择配置了的 `C++ Debug`,并 开始调试。
在以上步骤中,确保路径、文件名根据你项目的实际情况作出相应地更改。如果你的项目构建和调 试设置更加复杂,可能需要进行进一步的自定义配置。