在 Windows 上配置 VS Code 的编译环境涉及安装编译器、配置 VS Code 以及编写和运行代码。以下是具体的步骤:
步骤 1:安装必要的软件
-
安装 Visual Studio Code:
- 访问 VS Code 的官方网站并下载安装包。
- 按照安装向导进行安装。
-
安装 C/C++ 编译器:
- 访问 MinGW-w64 网站并下载最新的安装包。
- 安装 MinGW-w64,并确保选择
mingw32-base
和mingw32-gcc-g++
包。
-
配置系统环境变量:
- 打开系统属性 -> 高级系统设置 -> 环境变量。
- 在系统变量中找到
Path
,然后编辑,将 MinGW-w64 的bin
目录路径添加到Path
中。例如:C:\Program Files\mingw-w64\...\mingw64\bin
。
步骤 2:配置 VS Code
-
安装 C/C++ 扩展:
- 打开 VS Code。
- 通过左侧的扩展视图(或按
Ctrl+Shift+X
),搜索并安装C/C++
扩展(Microsoft 开发的)。
-
创建配置文件:
- 打开或创建一个新的 C/C++ 项目文件夹。
- 在项目文件夹下创建一个
.vscode
文件夹。 - 在
.vscode
文件夹内创建以下文件:c_cpp_properties.json
:配置 IntelliSense。tasks.json
:配置构建任务。launch.json
:配置调试设置。
c_cpp_properties.json 示例
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "C:/Program Files/mingw-w64/.../mingw64/bin/gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
tasks.json 示例
{
"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": "Generated task by IntelliSense."
}
]
}
launch.json 示例
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ - 生成和调试活动文件",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:/Program Files/mingw-w64/.../mingw64/bin/gdb.exe",
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build",
"internalConsoleOptions": "neverOpen"
}
]
}
步骤 3:编写和运行代码
- 创建 C/C++ 文件:
- 在项目文件夹中创建一个新的
.cpp
文件,例如main.cpp
。 - 编写一些简单的 C++ 代码,例如
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
- 编译和运行代码:
- 按
Ctrl+Shift+B
编译代码。这将使用tasks.json
中定义的任务。 - 按
F5
运行和调试代码。这将使用launch.json
中定义的配置。
- 按
-
完整的设置流程
- 安装 VS Code 和 MinGW-w64。
- 配置系统环境变量。
- 在 VS Code 中安装 C/C++ 扩展。
- 配置
.vscode
文件夹中的c_cpp_properties.json
、tasks.json
和launch.json
。 - 编写并运行 C++ 代码。
- 在项目文件夹中创建一个新的
这样,你就成功地在 Windows 上配置了 VS Code 的编译环境,并可以开始进行 C/C++ 开发了。