windowsy官网地址:https://code.visualstudio.com/docs/cpp/config-mingw
vscode用wsl:https://code.visualstudio.com/docs/cpp/config-wsl(本文不涉及,用于后续研究)
以win10 64位为例
1.安装vscode
此处省略
2.在vscode中安装c/c++插件
在vscode中安装如下 插件
3.windows系统下,安装编译器(MinGW-x64)
MinGW-x64是windows下的编译开发环境,提供一个terminal窗口供用户编译、调试。
-
安装(参考网址https://www.jianshu.com/p/e79cdf4c32ef)
网址:https://www.msys2.org/。 -
安装需要的工具链
需要在 MinGW-x64中执行以下语句(坑1: 一定要执行,否则没有gdb):
pacman -S --needed base-devel mingw-w64-x86_64-toolchain
- 将MinGW 编译器的路径添加到环境变量“path”中**
C:\msys64\
# add gdb env to path
C:\msys64\mingw64\bin
- 在MinGW-x64中执行,一下命令,查看是否可以正常调用g++,gdb。
gcc --version
g++ --version
gdb --version
Administrator@I6HCU75VXKC3B6C MINGW64 ~
# gcc --version
gcc.exe (Rev4, Built by MSYS2 project) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Administrator@I6HCU75VXKC3B6C MINGW64 ~
# g++ --version
g++.exe (Rev4, Built by MSYS2 project) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Administrator@I6HCU75VXKC3B6C MINGW64 ~
# gdb --version
GNU gdb (GDB) 12.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
mingw官方下载地址:https://osdn.net/projects/mingw/releases/
4.vscode中,创建hello world项目
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .
- 添加helloworld.cpp
// 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;
}
界面如下:
其中,.vscode 需要用一下命令生成,坑2: 一定要执行,否则生成不了。
ctrl + shift + e
4.1 运行helloworld.cpp
-
打开 helloworld.cpp,告诉vscode这是当前活跃文件。
-
点击右上角三角, 选择Run C/C++ File
选完之后,如下图,如过下次操作还是run,可以直接点击三角,而不用下拉列表里再选择。
-
在下拉列表中选中绿色框中的编译器。如图中的g++,选中后会在tasks.json中设置成默认的。
运行之后的输出结果
4.2 调试helloworld 项目
- 同样打开 helloworld.cpp ,设定为活跃文件
- 打断点,鼠标点击左侧,或者选中当前行,然后F9.
- 右上角三角,下拉列表里选择**“Debug C/C++ File”**
这里需要注意,选中之后,图标变成了小虫子,如果下次还是debug,可以直接点虫子,不用在下拉列表里选择。
- 选择编译器
5. json文件
-
task.json
Run对应的json文件。type是cppbuild。
这个文件用于设置编译的参数,输出的文件名字
-
launch.json
Debug对应的json文件。
type是cppdbg。
这个文件用于设置需要调试的可执行文件;调试工具的位置,比如gdb.exe;是否默认main函数打断点,等等。
此外, 可以设置prelauch,也就是在debug之前执行一些东西。
-
c_cpp_properties.json
c++的配置文件。用于设置编译器的路径、c++标准、包含路径等。
6. 在vscode中修改默认的terminal
- 调出terminal
ctrl + `
- 点击右侧三角,下拉列表,配置终端设置。
弹出如下窗口
选择红圈中的图标,
弹出终端设置json
一共5个,箭头所指的是默认的。
坑:
(1)git bash终端会在run、debug时候有问题,禁用。
(2)wsl的也会有问题,用wsl调试本地文件。感觉文章开头提到的https://code.visualstudio.com/docs/cpp/config-wsl,应该能够解决。相当于用vscode终端远程访问wsl,在wsl中做debug。