环境搭建:安装 g++ 与 IDE
Windows/macOS/Linux 安装 g++、VS Code 配置 C++ 开发环境、第一个编译运行
环境搭建:安装 g++ 与 IDE
C++ 的开发环境需要 C++ 编译器(g++/clang++/MSVC)和一个好用的编辑器。好在所有主流 OS 都能免费搭建。
学完本章你将: 掌握 Windows/macOS/Linux 安装 g++、VS Code 配置 C++ 开发环境。
Windows 安装 g++
方式 1:MSYS2(推荐)
- 下载安装 MSYS2
- 在 MSYS2 终端中:
bash
pacman -S mingw-w64-ucrt-x86_64-gcc
# g++ 包含在 gcc 包里
- 将
C:\msys64\ucrt64\bin添加到 PATH - 验证:
bash
g++ --version
g++ --version
方式 2:安装 Visual Studio
VS 2022 Community(免费)自带 MSVC 编译器,适合 Windows 原生开发。
macOS 安装 g++
bash
# 安装 Xcode CLT(自带 clang++,对 C++ 支持优秀)
xcode-select --install
# 或 GNU g++
brew install gcc
# 验证
g++ --version
clang++ --version
Linux 安装 g++
bash
# Ubuntu/Debian
sudo apt install build-essential
# build-essential 包含 gcc/g++/make 等整套工具
# 验证
g++ --version
VS Code 配置 C++ 开发环境
- 安装 VS Code 扩展:C/C++(Microsoft)
- 创建
hello.cpp:
cpp
#include <iostream>
int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}
- 按
F5→ 选 "C++ (GDB/LLDB)" → "g++" → VS Code 自动生成配置文件 Ctrl+F5运行,F5调试
指定 C++ 标准编译
bash
g++ -std=c++17 hello.cpp -o hello # C++17
g++ -std=c++20 hello.cpp -o hello # C++20
# 推荐加上警告
g++ -std=c++17 -Wall -Wextra hello.cpp -o hello
💡 始终用
-std=指定标准版本。不同编译器默认的标准不同,未指定可能导致语法报错。