文件结构

在一个cpp项目中,文件结构如下:

1
2
3
4
5
6
7
8
*
|-- .vscode/
| |-- setting.json
| |-- launch.json
| |-- tasks.json
|-- bin/
|-- CMakeLists.txt
|-- main.cpp

你需要修改的配置都在 .vscode/ 目录下面,在那里面修改对应配置

这里创建了一个 bin/ 目录用于存放临时生成的可执行文件

记得要先创建文件夹

tasks.json 内容示例

tasks.json 用于指明编译、运行的配置,同样记得修改command为你自己的路径,并且把mingw的bin目录添加到path。并且记得在你的项目文件夹下面把 bin/ 目录创建好

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"${file}",
"-o",
"${fileDirname}\\bin\\${fileBasenameNoExtension}.exe",
"-g",
"-Wall",
"-static-libgcc",
"-fexec-charset=GBK",
"-std=c++17"
],
"group": "build",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "new"
},
"problemMatcher": "$gcc"
},
{
"label": "run",
"type": "shell",
"command": "${fileDirname}\\bin\\${fileBasenameNoExtension}.exe",
"group": {
"kind": "test",
"isDefault": true
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "new"
}
},
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "D:\\Environment\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\bin\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
]
}

launch.json 内容示例

launch.json 主要用于调试,注意修改 miDebuggerPath 为你的 gdb 路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"version": "0.2.0",
"configurations": [
{ //这个大括号里是我们的‘调试(Debug)’配置
"name": "Debug", // 配置名称
"type": "cppdbg", // 配置类型,cppdbg对应cpptools提供的调试功能;可以认为此处只能是cppdbg
"request": "launch", // 请求配置类型,可以为launch(启动)或attach(附加)
"program": "${fileDirname}\\bin\\${fileBasenameNoExtension}.exe", // 将要进行调试的程序的路径
"args": [], // 程序调试时传递给程序的命令行参数,这里设为空即可
"stopAtEntry": false, // 设为true时程序将暂停在程序入口处,相当于在main上打断点
"cwd": "${fileDirname}", // 调试程序时的工作目录,此处为源码文件所在目录
"environment": [], // 环境变量,这里设为空即可
"externalConsole": false, // 为true时使用单独的cmd窗口,跳出小黑框;设为false则是用vscode的内置终端,建议用内置终端
"internalConsoleOptions": "neverOpen", // 如果不设为neverOpen,调试时会跳到“调试控制台”选项卡,新手调试用不到
"MIMode": "gdb", // 指定连接的调试器,gdb是minGW中的调试程序
"miDebuggerPath": "D:\\Environment\\mingw64\\bin\\gdb.exe", // 指定调试器所在路径,如果你的minGW装在别的地方,则要改成你自己的路径,注意间隔是\\
"preLaunchTask": "build" // 调试开始前执行的任务,我们在调试前要编译构建。与tasks.json的label相对应,名字要一样
}
]
}