C++26 Freestanding 库扩展详解:无操作系统也能用标准库

本文是「C++26 新特性单篇精讲」系列第 27 篇。阅读约需 6 分钟,文末可跳转完整合订本。


一、是什么

Freestanding C++ 是指不依赖操作系统运行时的 C++ 环境,如内核、引导程序、嵌入式固件、GPU 核函数。C++26 大幅扩展了 Freestanding 可用的标准库子集。


二、为什么需要它

传统上,Freestanding 环境只能使用极少量头文件(如 <limits><cstddef>),大量基础容器和算法无法使用。C++26 让 arrayspanexpectedoptionalvariant 等更多设施进入 Freestanding。


三、完整代码示例

// 假设处于 freestanding 环境
#include <array>
#include <optional>
#include <span>
#include <utility>

constexpr std::array<int, 4> data{1, 2, 3, 4};

std::optional<int> find(std::span<const int> s, int target) {
    for (int x : s) {
        if (x == target) return x;
    }
    return std::nullopt;
}

int main() {
    auto result = find(data, 3);
    return result.value_or(-1);
}

四、编译器支持与特性测试宏

编译器 状态
GCC 部分支持
Clang 部分支持
MSVC 部分支持

Freestanding 通常需要特殊编译选项(如 -ffreestanding)。


五、常见陷阱

  1. 没有 new/delete:Freestanding 不一定提供动态内存分配;
  2. 没有异常处理:依赖 RTTI 和异常的设施可能不可用;
  3. 需要显式指定 freestanding 模式:不是自动生效的。

六、小结

Freestanding 扩展让标准库真正覆盖到操作系统以下的层级。对内核开发、嵌入式、异构计算意义重大。


  • 返回 C++26 新特性全景合订本C++26 新特性全景解析
  • C/C++ 后台架构学习社区,欢迎关注: https://github.com/0voice

本文基于 C++26 已批准特性撰写,具体实现以编译器文档为准。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐