Ch 2: 开发环境搭建
- 选择合适的 C++ 编译器
- 配置构建工具 CMake
- 设置开发环境
- 理解 C++ 标准版本
2.1 编译器选择
Section titled “2.1 编译器选择”Python 不需要编译器
Section titled “Python 不需要编译器”Python 是解释型语言,代码直接由 Python 解释器执行:
# Python - 直接运行,无需编译python script.pypython -m http.server 8080python -c "print('Hello')"解释器负责:
- 解析 Python 代码
- 编译成字节码(.pyc)
- 执行字节码
C++ 需要编译器
Section titled “C++ 需要编译器”C++ 是编译型语言,代码需要先编译成机器码:
# C++ - 编译 + 运行g++ -std=c++20 main.cpp -o main./main编译器负责:
- 解析 C++ 代码
- 类型检查
- 生成目标代码
- 链接库文件
GCC (GNU Compiler Collection)
Section titled “GCC (GNU Compiler Collection)”Linux 和 macOS(通过 Xcode)都可使用:
# 检查版本g++ --version
# 编译g++ -std=c++20 main.cpp -o main
# 常用选项g++ -Wall -Wextra -O2 -std=c++20 main.cpp -o main# -Wall: 启用所有警告# -Wextra: 额外警告# -O2: 优化级别Clang (LLVM C++)
Section titled “Clang (LLVM C++)”macOS 默认的 C++ 编译器:
# 检查版本clang++ --version
# 编译clang++ -std=c++20 main.cpp -o main
# macOS 上通常指向 Apple ClangMSVC (Microsoft Visual C++)
Section titled “MSVC (Microsoft Visual C++)”Windows 上的选择:
# 使用 Visual Studio Developer Command Promptcl /std:c++20 main.cpp /Fe:main.exe
# 或使用 MSYS2/MinGWpacman -S mingw-w64-clang版本选择建议
Section titled “版本选择建议”| 平台 | 推荐编译器 | 版本要求 |
|---|---|---|
| macOS | Xcode Command Line Tools (Clang) | Clang 15+ 支持 C++20 |
| Linux | GCC | GCC 11+ 支持 C++20 |
| Windows | Visual Studio 2022 / MSVC | MSVC 2022 支持 C++20 |
2.2 构建工具 CMake
Section titled “2.2 构建工具 CMake”Python 的 pip/poetry
Section titled “Python 的 pip/poetry”Python 使用包管理器安装依赖:
# pippip install requestspip freeze > requirements.txtpip install -r requirements.txt
# poetrypoetry add requestspoetry installpoetry export -f requirements.txtCMake 是 C++ 的标准构建系统,它不是编译器,而是一个”构建文件生成器”:
cmake_minimum_required(VERSION 3.16)project(StdLibDemo LANGUAGES CXX)
# 设置 C++ 标准set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 添加可执行文件add_executable(myapp main.cpp)CMake 的工作流程:
CMakeLists.txt (人类可读) ↓ cmake 命令Makefile / Ninja / MSBuild (机器生成) ↓ make/ninja/msbuild可执行文件CMake 详细配置
Section titled “CMake 详细配置”cmake_minimum_required(VERSION 3.16)project(MyProject VERSION 1.0.0 LANGUAGES CXX)
# C++ 标准set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)set(CMAKE_CXX_EXTENSIONS OFF)
# 优化和警告if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic")endif()
# 搜索库find_package(Threads REQUIRED)
# 添加可执行文件add_executable(myapp src/main.cpp src/utils.cpp include/utils.h)
# 链接库target_link_libraries(myapp PRIVATE Threads::Threads)# 创建构建目录(不要在源码目录构建!)mkdir build && cd build
# 配置(生成构建文件)cmake .. # 或 cmake -S . -B build
# 编译cmake --build . # 或 make / ninja
# 或一步完成cmake .. && cmake --build .
# 清理rm -rf build2.3 IDE 和编辑器
Section titled “2.3 IDE 和编辑器”VS Code
Section titled “VS Code”轻量级但功能强大:
必需扩展:
C/C++(Microsoft)CMake Tools(Microsoft)
配置示例:
{ "configurations": [{ "name": "Mac", "compilerPath": "/usr/bin/clang++", "cppStandard": "c++20", "intelliSenseMode": "macos-clang-arm64" }]}JetBrains 出品的专业 C++ IDE:
- 原生支持 CMake
- 智能代码补全
- 调试器集成
Visual Studio
Section titled “Visual Studio”Windows 上的完整 IDE:
- 安装时选择”使用 C++ 的桌面开发”
- 内置 MSVC 编译器
- 丰富的调试功能
2.4 C++ 标准版本详解
Section titled “2.4 C++ 标准版本详解”为什么标准版本重要
Section titled “为什么标准版本重要”不同标准支持不同特性:
// C++11 之前for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { // 繁琐的迭代器写法}
// C++11 - 范围 forfor (int x : v) { // 简洁}
// C++20 - auto 推导for (auto x : v) { // 更简洁 std::cout << x << std::endl;}各版本重要特性
Section titled “各版本重要特性”C++11(现代 C++ 起点):
auto x = 5; // 类型推导auto lambda = [](int x) { return x * 2; }; // Lambdastd::shared_ptr<int> sp; // 智能指针std::move(x); // 移动语义C++14:
auto lambda = [](auto x) { return x * 2; }; // 泛型 Lambdaconstexpr int fib(int n) { return n <= 1 ? n : fib(n-1) + fib(n-2); }C++17:
if (auto it = m.find(key); it != m.end()) { // if 初始化 auto [k, v] = *it; // 结构化绑定}std::optional<int> opt; // 可选值std::variant<int, float> v; // 联合体C++20(本书默认):
template<std::integral T> // Conceptsauto result = nums | std::views::filter(...); // Rangesstd::format("{}", 42); // 格式化co_await std::suspend_always{}; // 协程C++23:
std::expected<int, Error> result; // 错误处理auto view = nums | std::ranges::to<std::vector>(); // Ranges to2.5 第一个完整示例
Section titled “2.5 第一个完整示例”my_stdlib_demo/├── CMakeLists.txt├── src/│ └── main.cpp└── build/CMakeLists.txt
Section titled “CMakeLists.txt”cmake_minimum_required(VERSION 3.16)project(StdLibDemo VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(myapp src/main.cpp)main.cpp
Section titled “main.cpp”#include <iostream>#include <vector>#include <algorithm>#include <string>
int main() { // 演示标准库用法 std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
// 遍历(C++11 范围 for) std::cout << "Names: "; for (const auto& name : names) { std::cout << name << " "; } std::cout << std::endl;
// 排序(C++11 Lambda) std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) { return a.length() < b.length(); });
std::cout << "Sorted by length: "; for (const auto& name : names) { std::cout << name << " "; } std::cout << std::endl;
return 0;}mkdir build && cd buildcmake ..cmake --build ../myapp2.6 常见编译错误
Section titled “2.6 常见编译错误”未声明的标识符
Section titled “未声明的标识符”// 错误std::vector<int> v{1, 2, 3};sort(v.begin(), v.end()); // 错误:sort 在 std 命名空间
// 正确std::sort(v.begin(), v.end());缺少 include
Section titled “缺少 include”// 错误std::string s = "hello";std::cout << s << std::endl;
// 正确#include <string>#include <iostream>C++ 版本不匹配
Section titled “C++ 版本不匹配”// 如果编译器不支持 C++20// std::format 可能不可用
// 检查是否支持#if __cplusplus >= 202002L std::cout << std::format("C++20\n");#else std::cout << "Pre-C++20\n";#endif- C++ 需要显式编译,编译器将代码翻译成机器码
- CMake 是标准构建系统,跨平台支持好
- C++20 是当前主流版本,具备完整的现代特性
- 编译时检查能提前发现错误
- 常见的编译错误包括:未声明标识符、缺少 include、标准版本不匹配
下章预告:ch03 字符串和文本处理。