# vscode配置C++环境
# 1. 安装 VS Code
根据你的系统选择:
- Windows:下载
.exe
安装包 - macOS:下载
.zip
或.dmg
- Linux:下载
.deb
或.rpm
- Windows:下载
安装时勾选:
- 「Add to PATH」
- 「Register Code as an editor for supported file types」
- 「Add 'Open with Code' to context menu」
这样你可以直接在命令行里用 code
打开文件夹。
# 2. 安装 C/C++ 编译器
VS Code 只是编辑器,编译器需要你自己装。不同系统方法不同。
# Windows
推荐安装 MinGW-w64:
下载地址: https://winlibs.com/ (opens new window)(推荐) 选择
UCRT runtime
版本,解压到C:\mingw64
(比如)。配置环境变量:
右键「此电脑」→「属性」→「高级系统设置」→「环境变量」
在「系统变量」找到
Path
,添加:C:\mingw64\bin
检查是否安装成功:
g++ --version
能输出版本号就说明成功。
# macOS
打开终端,运行:
xcode-select --install
这会安装
clang
编译器。检查:
clang --version
# Linux (Ubuntu/Debian)
在终端运行:
sudo apt update sudo apt install build-essential
检查:
g++ --version
# 3. 安装 VS Code 必备插件
打开 VS Code → 左侧扩展(Ctrl+Shift+X)搜索安装:
- C/C++(Microsoft 官方,提供语法高亮、智能提示)
- Code Runner(方便一键运行代码)
- CMake Tools(如果你打算以后做大型项目或用 CMake)
# 4. 配置与运行
我给你两种方式:
# 方式 1:用 Code Runner 快速运行(新手方便)
新建一个
.cpp
文件,比如:#include <iostream> using namespace std; int main() { cout << "Hello, VS Code!" << endl; return 0; }
保存文件(Ctrl+S)。
点击右上角的 小三角“Run Code” 按钮(或 Ctrl+Alt+N)即可运行。 注意:Code Runner 默认会在下方终端显示输出。
# 方式 2:用 tasks.json 和 launch.json 手动配置(更专业)
这样可以自己控制编译、调试过程。
# ① 生成配置文件
- 按
Ctrl+Shift+P
→ 输入C/C++: Edit Configurations (UI)
,选择你的编译器路径。 - 在项目根目录下新建
.vscode
文件夹(VS Code 会自动生成)。
# ② 创建 tasks.json(编译任务)
Ctrl+Shift+P
→ 输入 Tasks: Configure Task
→ 选择 Create tasks.json file from template
→ 选择 Others
,修改为:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.exe"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "编译 C++ 程序"
}
]
}
# ③ 创建 launch.json(调试配置)
按 F5
→ 选择 C++ (GDB/LLDB)
→ 选择 g++
→ 修改为:
{
"version": "0.2.0",
"configurations": [
{
"name": "调试 C++",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "gdb",
"preLaunchTask": "build"
}
]
}
这样:
Ctrl+Shift+B
→ 编译F5
→ 编译并调试(会弹出独立终端)
# 5. 常见问题
g++ 不是内部或外部命令:说明没配置 PATH,回到第 2 步检查。
中文输出乱码(Windows):
在代码最上面加:
#include <windows.h>
然后:
SetConsoleOutputCP(65001);
或者在终端里运行:
chcp 65001