环境设置
在vscode中为c++配置调试功能,需要有以下配置
- gcc/g++已经添加到了环境变量中环境变量中。
- vscode添加了C/C++扩展
三个配置文件设置
c_cpp_properties.json
该文件注意是告诉vscode编译器相关的信息。如果缺少该文件,或文件配置错误,可能出现
#include <iostream>
报错的问题,如图所示:
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"cStandard": "c17",
"cppStandard": "gnu++17",
"intelliSenseMode": "windows-gcc-x64",
"compilerPath": "C:/Program Files/mingw64/bin/g++.exe"
}
],
"version": 4
}
launch.json
该文件主要是告诉vscode调试器在哪里,以及调试器相关的配置。program中则存放的是文件所在的路径,
{
"version": "0.2.0",
"configurations": [
{
"name": "C++调试",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.exe", // 生成的exe文件路径
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}", // 将工作目录设置为当前文件所在的目录
"environment": [],
"externalConsole": false, // 如果需要外部控制台,可以设置为true
"MIMode": "gdb",
"miDebuggerPath": "C:/Program Files/mingw64/bin/gdb.exe", // 替换为你系统中的gdb路径
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "将反汇编风格设置为 Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
],
"preLaunchTask": "build" // 确保在调试前执行编译任务
}
]
}
tasks.json
cpp程序在运行之前需要先编译,因此在调试之前需要确保程序已经编译好。tasks中label对应的值build和launch.json中preLaunchTask对应的值build相呼应,表示在调试之前需要执行的任务。
而在tasks.json中,标签名为build的任务是使用g++编译器将当前的cpp文件编译为exe文件,注意参数列表args中不可缺少-o
指令,-o
指令可以保存调试信息,使用该指令才能让程序可调试。
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"${file}",
"-g",
"-o", //注意不要丢掉该指令,使用该指令可以保留调试信息,使得vscode能够对cpp编译的程序进行调试
"${fileDirname}/${fileBasenameNoExtension}.exe"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "Generated task for compiling current file."
}
]
}