MinGW-w64 - for 32 and 64 bit Windows - Browse /mingw-w64/mingw-w64-release at SourceForge.net
进入系统环境变量:
将MinGW的bin目录写进path,我的MinGW目录为:D:\Environments\mingw64\bin
进入cmd,输入gcc:
配置成功。
下载C/C++插件
在一个空文件夹(英文)下新建一个main.cpp,编写一个简单的程序:
#include <iostream> using namespace std; void swap(int &a, int &b); int main(int argc, char *argv[]) { int a{1}; int b{3}; cout << "实现两个数字交换" << endl; cout << "交换前a = " << a << ",b = " << b << endl; swap(a,b); cout << "交换后a = " << a << ",b = " << b << endl; return 0; } void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; }
{ "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "D:\\Environments\\mingw64\\bin\\gcc.exe", "cStandard": "gnu17", "cppStandard": "gnu++14", "intelliSenseMode": "windows-gcc-x64" } ], "version": 4 }
创建此文件来告诉VS Code如何构建(编译)程序。该任务将调用g++编译器基于源代码创建可执行文件。
按快捷键Ctrl+Shift+P调出命令面板,输入tasks,选择Tasks:Configure Default Build Task
再选择 C/C++: g++.exe build active file
此时就会生成一个tasks.json文件
{ "version": "2.0.0", "tasks": [ { "type": "shell", "label": "compile", // 任务名称,与launch.json的preLaunchTask相对应 "command": "D:\\Environments\\mingw64\\bin\\g++.exe", // 编译器的路径 // 编译c++文件使用g++.exe,c文件使用gcc.exe,此处编译c++文件 "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "D:\\Environments\\mingw64\\bin" }, "problemMatcher": [ "$gcc" ], "group": "build" } ], "presentation": { "panel": "new", //这里shared表示共享,改成new之后每个进程创建新的端口 } }
按如下代码配置即可:
{ "version": "0.2.0", "configurations": [ { "name": "g(gdb) Launch", // 配置名称,将会在启动配置的下拉菜单中显示 "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, //修改此项,让其弹出终端 "internalConsoleOptions": "neverOpen", // 如果不设为neverOpen,调试时会跳到“调试控制台”选项卡 "MIMode": "gdb", "miDebuggerPath": "D:\\Environments\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "compile" //修改此项 // 调试会话开始前执行的任务,一般为编译程序。与tasks.json的label相对应 } ] }
断点,按F5测试:
配置成功。
新建一个project文件夹(自己取名),用vscode打开,按快捷键Ctrl+Shift+P调出命令面板,输入Create C++ project(创建C++项目)或者输入Create C project(创建C项目)。
自动创建和配置项目。
参考:VScode配置C/C++环境 - laomaocode - 博客园 (cnblogs.com)