VS Code 配置 C/C++ 编程运行环境(保姆级教程)
一、安装编译器
-
下载 MinGW
访问 MinGW-w64 官网 下载安装包(选择
x86_64-posix-seh版本)mingw-w64-install.exe -
配置环境变量
将 MinGW 的
bin目录(例如C:\mingw64\bin)添加到系统环境变量PATH中:- 右键「此电脑」→ 属性 → 高级系统设置 → 环境变量
- 在「系统变量」中找到
PATH,点击编辑 → 新建 → 输入路径
二、安装 VS Code 及扩展
-
安装 VS Code
-
安装扩展
打开 VS Code,按
Ctrl+Shift+X,搜索并安装:C/C++(Microsoft 官方扩展)Code Runner(一键运行代码)
三、配置调试环境
-
创建工程目录
新建文件夹(例如
D:\cpp_project),在 VS Code 中打开此文件夹。 -
生成配置文件
按
Ctrl+Shift+P输入:C/C++: Edit Configurations (UI)在打开的界面中:
- 编译器路径 :输入
g++.exe的完整路径(例如C:\mingw64\bin\g++.exe) - IntelliSense 模式 :选择
gcc-x64
- 编译器路径 :输入
-
创建调试配置
创建
launch.json:-
点击左侧「运行和调试」图标 → 创建
launch.json文件 -
选择
C++ (GDB/LLDB) -
修改配置如下:
json{ "version": "0.2.0", "configurations": [ { "name": "g++.exe - 生成和调试活动文件", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "C:\\mingw64\\bin\\gdb.exe", "setupTasks": ["build"], "preLaunchTask": "build" } ] }
-
-
创建编译任务
生成
tasks.json:-
Ctrl+Shift+P→ 输入Tasks: Configure Task→ 选择「使用模板创建」→Others -
修改为:
json{ "version": "2.0.0", "tasks": [ { "label": "build", "type": "shell", "command": "g++", "args": ["-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"], "group": { "kind": "build", "isDefault": true } } ] }
-
四、测试运行
-
创建测试文件
新建
hello.cpp:cpp#include <iostream> using namespace std; int main() { cout << "Hello VS Code!" << endl; return 0; } -
编译运行
- 方法1(调试) :按
F5启动调试(自动编译并运行) - 方法2(快速运行) :右键代码 →
Run Code(需安装 Code Runner)
- 方法1(调试) :按
五、常见问题解决
- 报错「g++ not found」:检查环境变量配置,重启 VS Code
- 调试时闪退 :在
launch.json中设置"externalConsole": true - 中文乱码 :在
tasks.json的args中添加"-fexec-charset=GBK"
提示:按
Ctrl+可打开集成终端,直接输入命令编译:
bashg++ hello.cpp -o hello && ./hello
通过以上步骤,即可在 VS Code 中高效编写、调试 C/C++ 程序。