【问题标题】:Can't use iostream as module in C++20 (Visual Studio)不能在 C++20 (Visual Studio) 中使用 iostream 作为模块
【发布时间】:2020-11-17 14:50:09
【问题描述】:

无法在最新版本的 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'的标头单元

我使用的是 Microsoft Visual Studio 版本 16.8.1,并在项目属性中启用了这些标志(根据此处的类似问题 Standard way of importing modules):

  • /experimental:模块
  • /std:c++latest
  • /EHsc
  • /MD

谁能帮我解决这个问题?我应该改用 Clang 还是 GCC?

【问题讨论】:

  • 截至 2020 年 10 月 29 日,how to use modules in Visual Studio 上的说明仅提及/std:c++latest。您可以在禁用其他标志后重试吗?特别是/experimental:module 可能会干扰
  • 仍然出现同样的错误:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\iostream" is not an importable header
  • 上述链接中 2020 年 10 月 29 日的说明似乎没有使用任何 std 库作为模块。它仍然使用#include &lt;iostream&gt;

标签: c++ c++20


【解决方案1】:

使用 Visual Studio 2019 非预览版:

  1. 创建一个空的 C++ 项目

  2. 打开项目属性Alt + Enter

  3. 转到Configuration Properties -&gt; C/C++ -&gt; Language,并将 C++ 语言标准选项设置为预览 - 最新 C++ 的功能

  4. 在同一部分将 Enable Experimental C++ Standard Library Modules 设置为 Yes (/experimental:module)

  5. 转到 Configuration Properties -&gt; C/C++ -&gt; Advanced 并将 Compile As 选项设置为 Compile as C++ Module Internal Partition (/internalPartition)

  6. 将头文件添加到您的项目中,其中包含您要导入的每个标准库头的导入声明。例如:

    #pragma once
    import <iostream>;
    import <array>;
    import <vector>;
    
  7. 重新编译你的项目

  8. 完成,现在一切正常

【讨论】:

    【解决方案2】:

    作者在提供下载的示例和解决方案文件中指出,由于 编译器对 C++ 20 标准的实现,这些文件可能还不能工作。 (详见book's pagecorresponding github repo)。

    因此,它们提供了利用“#include”指令的“无模块”示例。

    HTH。

    问候, 格伦那文

    【讨论】:

      【解决方案3】:

      尝试这样做:import &lt;iostream&gt;; // import declaration

      模块有助于将大量代码划分为逻辑部分。 模块与命名空间正交。

      示例

      helloworld.cpp

      export module helloworld;  // module declaration
      import <iostream>;         // import declaration
       
      export void hello() {      // export declaration
          std::cout << "Hello world!\n";
      }
      

      main.cpp

      import helloworld;  // import declaration
       
      int main() {
          hello();
      }
      

      【讨论】:

      • 还是不行。 IntelliSense 为我突出显示红色 iostream。
      • 它可以编译吗?智能感知并不总是正确的。
      • 不。我什至无法编译它。仍然得到同样的错误。 Idk,也许 GCC 和 Clang 是一个更好的解决方案?甚至本书的作者也提醒我,其中一些新功能可能不支持但是,大声笑,IntelliSense 突出了关键字导入,所以,idk
      • 我刚刚测试过,但它对我也不起作用,但我现在不在16.8.1,我不想冒险升级,因为没有简单的方法可以在不恢复的情况下再次降级点或备份和恢复。
      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2021-02-23
      • 2020-10-07
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2015-11-08
      相关资源
      最近更新 更多