模块系统

C++20 引入的模块(Modules)系统是编译模型的根本性变革。它用语义化的 import/export 替代文本粘贴式的 #include,消除了头文件带来的宏泄漏、重复解析和编译缓慢等问题。

#include 的问题

传统头文件机制存在深刻的设计缺陷:

// problem.cpp
#include <vector>       // 展开约 10,000+ 行
#include <algorithm>    // 再展开 10,000+ 行
#include <iostream>     // 又是 30,000+ 行
// 你的 10 行代码...编译器实际处理了 50,000+ 行!

#include 的具体问题

  • 文本粘贴:预处理器将头文件内容逐字复制到每个包含它的翻译单元
  • 重复解析:100 个 .cpp 文件 include 同一个头文件 = 解析 100 次
  • 宏泄漏:头文件中的 #define 污染所有后续代码(如 Windows.h 的 min/max)
  • 顺序依赖:#include 的顺序可能影响编译结果
  • ODR 违反:不同翻译单元看到不同的头文件版本导致 One Definition Rule 违反
  • 编译缓慢:大型项目中头文件展开是编译时间的主要瓶颈

模块基础语法

模块接口单元

模块接口单元(Module Interface Unit)声明模块名称并导出公开的声明:

// math.cppm(或 math.ixx,取决于编译器)
export module math;    // 声明这是模块 "math" 的接口单元

// export 标记公开的声明
export int add(int a, int b) {
    return a + b;
}

export int multiply(int a, int b) {
    return a * b;
}

// 没有 export 的声明:模块内部可见,外部不可见
int internal_helper(int x) {
    return x * x;
}

导入模块

// main.cpp
import math;           // 导入 math 模块
#include <iostream>    // 传统头文件仍可混用

int main() {
    std::cout << add(3, 4) << "\n";        // OK: add 已导出
    std::cout << multiply(3, 4) << "\n";   // OK: multiply 已导出
    // internal_helper(5);  // 错误!未导出,外部不可见
}

模块的关键优势

  • 模块只编译一次,生成二进制模块接口(BMI),后续导入直接使用 BMI
  • 模块内部的宏不会泄漏到导入方
  • import 的顺序不影响编译结果
  • 未导出的声明对外完全不可见(真正的封装)

模块接口与实现分离

// === math.cppm:接口单元 ===
export module math;

export int add(int a, int b);       // 只声明
export int multiply(int a, int b);  // 只声明

export class Calculator {
public:
    void push(double value);
    double result() const;
private:
    double accumulator_ = 0;
};


// === math.cpp:实现单元 ===
module math;    // 注意:没有 export,这是实现单元

int add(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    return a * b;
}

void Calculator::push(double value) {
    accumulator_ += value;
}

double Calculator::result() const {
    return accumulator_;
}

模块分区(Partitions)

大型模块可以拆分为多个分区,分区只在模块内部可见:

// === math:types.cppm(分区接口) ===
export module math:types;

export struct Vector2 {
    double x, y;
};

export struct Matrix2x2 {
    double data[2][2];
};


// === math:ops.cppm(另一个分区) ===
export module math:ops;
import :types;   // 导入同模块的分区(用冒号前缀)

export Vector2 add(Vector2 a, Vector2 b) {
    return {a.x + b.x, a.y + b.y};
}

export Vector2 transform(const Matrix2x2& m, Vector2 v) {
    return {
        m.data[0][0] * v.x + m.data[0][1] * v.y,
        m.data[1][0] * v.x + m.data[1][1] * v.y
    };
}


// === math.cppm(主接口,重新导出所有分区) ===
export module math;
export import :types;   // 重新导出分区
export import :ops;

import std;(C++23)

C++23 引入了 import std;,一条语句导入整个标准库:

// C++23:极简的模块化代码
import std;

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5};
    std::ranges::sort(nums);
    std::println("排序后: {}", nums);  // C++23 print
}

import std 的编译速度

在支持的编译器上,import std; 通常比包含单个 <vector> 头文件还快,因为标准库模块只构建一次。MSVC 实测:从 2.5 秒降至 0.3 秒(大型项目)。

渐进式迁移策略

不必一次性将整个项目迁移到模块。推荐的渐进路线:

  1. 第一步:在新代码中使用 import std;(如果编译器支持)
  2. 第二步:将内部工具库转为模块(影响范围小)
  3. 第三步:使用 header units 包装第三方头文件
  4. 第四步:逐步将核心库迁移为模块
// Header Unit:将传统头文件作为模块导入
import <vector>;      // 将 <vector> 当作 header unit 导入
import <string>;      // 编译器会缓存解析结果

// 混合使用:module + 传统头文件
export module mylib;
import <third_party/json.hpp>;   // 第三方库作为 header unit

export class Config {
    // ... 使用 json 库
};

CMake 模块支持

CMake 3.28+ 提供了实验性的 C++ 模块支持:

cmake_minimum_required(VERSION 3.28)
project(my_module_project CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 启用模块扫描
set(CMAKE_CXX_SCAN_FOR_MODULES ON)

# 添加库(包含模块接口文件)
add_library(math_lib)
target_sources(math_lib
    PUBLIC
        FILE_SET CXX_MODULES FILES
            src/math.cppm
            src/math-types.cppm
            src/math-ops.cppm
)

# 使用模块的可执行文件
add_executable(app src/main.cpp)
target_link_libraries(app PRIVATE math_lib)

编译器支持现状

特性 MSVC 17.6+ GCC 14+ Clang 18+
基本模块(export/import) 完整支持 完整支持 完整支持
模块分区 完整支持 完整支持 完整支持
Header Units 完整支持 部分支持 部分支持
import std; (C++23) 完整支持 GCC 15 实验性 Clang 18 实验性
CMake 集成 稳定 CMake 3.28+ 实验性 CMake 3.28+ 实验性
模块接口文件扩展名 .ixx .cppm .cppm

实际使用建议

  • MSVC 的模块支持最成熟,生产项目可以考虑使用
  • GCC/Clang 的模块支持在快速改进中,但跨编译器的可移植性仍需注意
  • 构建系统(CMake、Ninja)需要理解模块间的依赖关系来正确排序编译
  • 第三方库大多尚未提供模块接口,短期内仍需混合使用 #include

完整示例:模块化的小型库

// === geometry.cppm ===
export module geometry;

export import :point;
export import :shapes;

// === geometry:point.cppm ===
export module geometry:point;
import std;

export struct Point {
    double x = 0, y = 0;

    double distance_to(Point other) const {
        auto dx = x - other.x;
        auto dy = y - other.y;
        return std::sqrt(dx * dx + dy * dy);
    }
};

export Point operator+(Point a, Point b) {
    return {a.x + b.x, a.y + b.y};
}

// === geometry:shapes.cppm ===
export module geometry:shapes;
import :point;
import std;

export class Circle {
    Point center_;
    double radius_;
public:
    Circle(Point c, double r) : center_(c), radius_(r) {}
    double area() const { return std::numbers::pi * radius_ * radius_; }
    bool contains(Point p) const {
        return center_.distance_to(p) <= radius_;
    }
};

// === main.cpp ===
import geometry;
import std;

int main() {
    Point p1{0, 0}, p2{3, 4};
    std::println("距离: {}", p1.distance_to(p2));  // 5

    Circle c{p1, 5.0};
    std::println("面积: {:.2f}", c.area());
    std::println("p2 在圆内: {}", c.contains(p2));
}

本章小结

  • C++20 模块通过 export module / import 替代 #include,消除宏泄漏和重复解析
  • 模块接口单元声明公开 API,实现单元包含具体实现,分区拆分大型模块
  • C++23 的 import std; 可一次导入整个标准库,编译速度大幅提升
  • CMake 3.28+ 通过 FILE_SET CXX_MODULES 支持模块编译
  • MSVC 支持最成熟,GCC/Clang 快速跟进中;迁移应采取渐进策略