1. 调试配置选择
-
调试 C 程序:选择
"Debug C Program"
(调用gcc
编译)。 -
调试 C++ 程序:选择
"Debug C++ Program"
(调用g++
编译)。
2. 调试步骤
-
打开代码文件:确保当前编辑器打开的是
.c
或.cpp
文件。 -
设置断点:在代码行号左侧点击设置断点(红点)。
-
启动调试:
-
按
F5
或点击左侧调试图标 → 顶部下拉菜单选择调试配置(如Debug C Program
)→ 点击绿色箭头启动。
-
-
调试控制:
-
继续(F5):运行到下一个断点。
-
单步跳过(F10):执行当前行,不进入函数。
-
单步进入(F11):进入函数内部。
-
查看变量:在调试侧边栏的
VARIABLES
区域查看当前变量值。
-
3. 关键验证点
检查编译是否成功
-
调试前会自动执行
preLaunchTask
(即tasks.json
中的编译任务)。 -
如果编译失败:
-
检查终端输出错误(如语法错误)。
-
确保
gcc
/g++
命令在终端可直接运行(验证环境变量配置)。
-
检查调试器路径
-
Windows:若使用 MinGW,需将
miDebuggerPath
改为绝对路径(如"C:/TDM-GCC-64/bin/gdb.exe"
)。 -
Linux/macOS:
"gdb"
通常可用(确保已安装gdb
/lldb
)。
检查输出文件路径
-
你的配置将生成
.out
文件(如main.c
→main.out
),需与launch.json
的program
字段一致。
4. 常见问题解决
调试时提示“无法找到 .out 文件”
-
原因:编译失败或路径错误。
-
解决:
-
手动运行编译命令(如
gcc -g main.c -o main.out
)确认是否成功。 -
检查
${fileDirname}/${fileBasenameNoExtension}.out
路径是否正确。
-
断点未生效
-
确保编译时包含
-g
参数(生成调试信息)。 -
重新启动调试会话(有时需清理旧的可执行文件)。
Windows 下终端无输出
-
将
externalConsole
改为true
(部分 Windows 环境需要外部终端显示输出)。
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C Program",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false, // 改为 false 使用 VSCode 终端
"MIMode": "gdb",
"miDebuggerPath": "gdb", // Windows 改为 "C:/TDM-GCC-64/bin/gdb.exe"
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "gcc build active file" // 编译 C 文件
},
{
"name": "Debug C++ Program",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "gdb", // Windows 改为 "C:/TDM-GCC-64/bin/gdb.exe"
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file" // 编译 C++ 文件
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "gcc build active file",
"type": "shell",
"command": "gcc",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.out"
],
"group": "build",
"problemMatcher": [
"$gcc"
],
"detail": "编译当前 C 文件"
},
{
"label": "g++ build active file",
"type": "shell",
"command": "g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.out"
],
"group": "build",
"problemMatcher": [
"$gcc"
],
"detail": "编译当前 C++ 文件"
},
{
"type": "cppbuild",
"label": "C/C++: gcc.exe 生成活动文件",
"command": "C:\\TDM-GCC-64\\bin\\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
]
}