繁体   English   中英

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

[英]Can't use iostream as module in C++20 (Visual Studio)

我无法让这段代码在最新版本的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非预览版:

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

  2. 打开项目属性: Alt + Enter

  3. 转到Configuration PropertiesC/C++Language ,然后将C++ Language Standard选项设置为Preview - Features from the Latest C++

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

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

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

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

  8. 完成,现在一切正常

作者在提供下载的示例和解决方案文件中指出,由于编译器对 C++20 标准的实现,这些文件可能还不能工作(有关详细信息和相应的 GitHub 存储库,请参见本书页面)。

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

C++20 中的模块 (Visual Studio)

如果您使用“模块”:

这将不起作用: 5. 转到Configuration PropertiesC/C++Advanced并将Compile As选项设置为Compile as C++ Module Internal Partition (/internalPartition)

这将起作用: 5. 转到Configuration PropertiesC/C++Advanced并将Compile As选项设置为Compile as C++ Module Code (/interface)

尝试这样做:

import <iostream>;         // 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM