c++ - 不能在 C++20 (Visual Studio) 中使用 iostream 作为模块

标签 c++ c++20

无法在最新版本的 MSVC 中运行此代码。此代码示例来自 Ivor Horton 和 Peter Van Weert 所著的《Beginning C++20, From Novice to Professional》一书。

import <iostream>;
int main()
{
    int answer {42};
    std::cout << "The answer to life, universe, and everything is " 
            << answer 
            << std::endl;
    return 0;
}
我收到此错误:找不到“C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\iostream”的 header 单元
我正在使用 Microsoft Visual Studio 版本 16.8.1,并在项目属性中启用了这些标志(根据此处的类似问题 Standard way of importing modules):
  • /实验:模块
  • /std:c++最新
  • /EHsc
  • /MD

  • 有人可以帮我吗?我应该改用 Clang 还是 GCC?

    最佳答案

    使用 Visual Studio 2019 非预览版:

  • 创建一个空的 C++ 项目
  • 打开项目属性Alt + Enter
  • 转至 Configuration Properties -> C/C++ -> Language ,并将 C++ 语言标准选项设置为预览 - 最新 C++ 的功能
  • 在同一部分中,将 Enable Experimental C++ Standard Library Modules 设置为 Yes (/experimental:module)
  • 转至 Configuration Properties -> C/C++ -> Advanced并将 Compile As 选项设置为 Compile as C++ Module Internal Partition (/internalPartition)
  • 将头文件添加到您的项目,其中包含您要导入的每个标准库头的导入声明。例如:
    #pragma once
    import <iostream>;
    import <array>;
    import <vector>;
    
  • 重新编译你的项目
  • 完成,现在一切正常
  • 关于c++ - 不能在 C++20 (Visual Studio) 中使用 iostream 作为模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64877559/

    相关文章:

    c++ - 当元素的成员为 const 时,在编译时初始化 std::array。自定义 to_array 实现

    c++ - 在 C++14、C++17、C++20 和不同的编译器中, float 和整数之间的按位转换是否有处理未定义行为的最佳方法?

    c++ - friend函数是如何在内部实现的

    c++ - 非依赖条件的条件 constexpr

    c++ - 在概念中表达对数据成员的概念要求的最佳方式是什么?

    c++ - 将 constexpr class static 映射到类集合的类

    c++ - c++ mac OS 中的自动化单元测试

    C++ 序列化性能

    c++ - 为什么标准不允许通过非常量引用传递临时变量?

    c++ - 如何正确编译/链接 Linux Makefile 中的单元测试?