C++20 Modules 模块
import/export 替代 #include、模块分区、编译速度提升
C++20 Modules 模块
#include 是文本复制——慢、污染命名空间、依赖头文件顺序。import 是真正的模块——编译快、不泄漏。
学完本章你将: 掌握 import/export 替代 #include、编译加速。
定义模块
cpp
// math.ixx(模块接口文件)
export module math; // 声明模块
export int add(int a, int b) { return a + b; }
export namespace math {
constexpr double PI = 3.1415926535;
double square(double x) { return x * x; }
}
// 不 export 的内容——模块外不可见
int internal_helper() { return 0; }
使用模块
cpp
// main.cpp
import math; // 替代 #include "math.h"
import <iostream>; // 标准库也能 import
int main() {
std::cout << add(3, 5) << "\n";
std::cout << math::PI << "\n";
// internal_helper(); // ❌ 不可访问
}
模块分区
cpp
// math.ixx
export module math;
export import :arithmetic; // 导出分区
export import :trigonometry;
// math-arithmetic.ixx
export module math:arithmetic; // 分区声明
export int add(int, int);
export int multiply(int, int);
include vs import
| #include | import | |
|---|---|---|
| 机制 | 文本复制 | 预编译二进制 |
| 编译速度 | 每次重新解析 | 只编译一次 |
| 符号泄漏 | 全部可见 | 只导出 export |
| 顺序依赖 | 有 | 无 |
| 支持 | 全部编译器 | C++20+(各编译器进度不一) |