在 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++ 開發了。