VS Code编译调试C/C++(Windows平台)
引言
微软的VS Code可以说是良心产品了,小巧轻便,适合中小型项目的开发(再也不用忍受Visual Studio的臃肿了)。VS Code本身是一个代码编辑器而非完整的IDE,现把它编译调试C/C++的方法记录如下。
下载安装MinGW
这里用MinGW作为C/C++编译器。下载:OSDN或SourceForge。
运行“MinGW Installer”,选择需要安装的组件(我安装了如下项),菜单“Installation - Apply Changes”,等待下载安装完成。
将MinGW安装目录下的bin文件夹添加到Path环境变量,如下(计算机 - 属性 - 高级系统设置 - 环境变量)。这样可以直接在命令行中使用g++等命令。
编写tasks.json文件
以C++为例,假设现在在VS Code中写好了一个hello.cpp文件。菜单“View - Command Palette”(Ctrl+Shift+P),搜索并选择“Tasks: Configure Task” - “others”,VS Code自动生成一个tasks.json文件,将其修改如下。该文件表示执行一个编译任务,相当于命令行“g++ -g hello.cpp
”。
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++",
"args": ["-g", "hello.cpp"]
}
]
}
编写launch.json文件
点击VS Code左侧的Debug图标,选择“C++ (GDB/LLDB)”作为Configuration,VS Code自动生成一个launch.json文件,将其修改如下。其中"miDebuggerPath"
指定为“MinGW安装目录\bin\gdb.exe”,"preLaunchTask": "echo"
对应tasks.json文件中的"label": "echo"
。这样可以在调试前自动执行tasks.json文件所说明的编译任务,生成“a.exe”,对应launch.json文件中的"program": "${workspaceFolder}/a.exe"
。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\\ProgramFiles\\MinGW\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "echo"
}
]
}
调试
在hello.cpp文件中设置好断点,按F5调试。应该可以调试成功啦。