一、环境配置
- 安装了vscode
- 安装了 C/C++
- 安装好了Mingw-w64工具,并设置好了环境变量
Mingw-w64是Windows下的GCC工具,检查是否安装好可以用以下命令:
g++ -v
gdb -v
二、创建工程
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code
code . 命令在当前目录下的打开vscode,创建helloworld.cpp文件
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
三、编译
1、tasks.json 文件
- 主菜单栏选择 Terminal -> Configure Default Build Task.
- 从下拉栏中选择 g++.exe build active file,来编译在编辑栏活跃的源文件。
tasks.json 文件告诉vscode如何编译这个程序,调用 g++ 编译器将源文件编译成可执行文件。
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "task g++",
"command": "D:\\path\\c++\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "D:\\path\\c++\\bin\\g++.exe"
},
]
}
2、launch.json 文件
- 从主菜单,选择 Run -> Add Configuration ... 之后选择 C++(GDB/LLDB)
- 从下拉栏中选择g++.exe build and debug active file.
- program:调试入口文件的地址
- cwd:程序启动调试的目录
- miDebuggerPath:调试器的路径
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Windows Bash ",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"pipeTransport": {
"debuggerPath": "/usr/bin/gdb",
"pipeProgram": "${env:windir}\\system32\\bash.exe",
"pipeArgs": ["-c"],
"pipeCwd": ""
},
"setupCommands": [
{
"description": "gdb description",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "task g++"
},
{
"name": "C/C++ Runner: Debug Session",
"type": "cppdbg",
"request": "launch",
"args": [
""
],
"stopAtEntry": true,
"cwd": "d:/code/projects/helloworld",
"environment": [],
"program": "${fileDirname}\\${fileBasenameNoExtension}",
"internalConsoleOptions": "openOnSessionStart",
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"externalConsole": true,
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "task g++"
}
]
}
注意:preLaunchTask
指定了在启动调试前应该执行的任务,因此应该和tasks.json文件中的label保持一致。
四、开始调试
按 F5 ,或者Run > Start Debugging 。