基于vscode与mingw配置c++环境(ACM向)

本篇博客与基于vscode与wsl配置c++环境(ACM向) 联动。

MinGW 相对 wsl 而言,小白使用更方便。

注:在windows环境使用powershell,所以一些地方与基于 wsl 的配置语法不一样。

MinGW

安装mingw应该不难。小白可以简单粗暴地下载 codeblocks-MinGW-nosetup 版本,解压后就有个 MinGW 目录

这里给个当前版本的SourceForge下载链接

都下载codeblocks了还用vscode干嘛?
之前我也这么想的,直到发现确实有人更想要vscode的界面与字体与配色,codeblocks配置半天还是没vscode养眼。

配置系统环境变量 path,添加 xxx/xxx/MinGW/bin

检查是否配置好,新打开powershell或cmd,gcc -v 有版本信息就是配好了。

目录设定

vscode 打开工作目录,比如 E:\cpp\localcpp,在此目录下新建一个workspace

最后的目录结构会是这样:

1
2
3
4
5
6
| .vscode           // vscode的配置文件,下文的tasks.json、launch.json都在这里
| workspace // 自己的工作目录
| --| build // 编译的结果会在这个目录
| --| main.cpp // 主文件
| otherfolder // 如果做成git仓库,可以这里归档自己的代码
| .gitignore // git仓库忽略的文件,可以忽略 .vscode 和 workspace 这两个目录

tasks.json

打开一个cpp文件,菜单的 Terminal(F1)打开 Configure Default Build Task...,选择g++ build active file

自动生成tasks.json,修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++.exe gen",
"command": "New-Item -ItemType Directory -Force -Path ${workspaceFolder}/workspace/build | Out-Null; g++ ${file} -g -o ${workspaceFolder}/workspace/build/${fileBasenameNoExtension}.exe; cd ${workspaceFolder}/workspace/build/; .\\${fileBasenameNoExtension}.exe",
"args": [],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"type": "shell",
"label": "g++ debug",
"command": "New-Item -ItemType Directory -Force -Path ${workspaceFolder}/workspace/build | Out-Null; g++ ${file} -g -o ${workspaceFolder}/workspace/build/${fileBasenameNoExtension}.exe;",
"args": [],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "none"
}
},
]
}

launch.json

菜单的 Run 打开 Add Configuration... 选择 C++ (GDB/LLDB)

自动生成launch.json,修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
// 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 start",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/workspace/build/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"preLaunchTask": "g++ debug",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}

使用

ctrl+shift+b 编译+运行,在vscode下方的terminal里进行数据交互

f5 debug,也在terminal里。其它debug快捷键点菜单的Run查看。