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

Viewed 6640

I can't get this code running in the newest version of MSVC. This code example is from the book called "Beginning C++20, From Novice to Professional" by Ivor Horton and Peter Van Weert.

import <iostream>;

int main()
{
    int answer {42};
    std::cout << "The answer to life, universe, and everything is "
              << answer
              << std::endl;
    return 0;
}

I get this error:

could not find header unit for 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\iostream'

I am using Microsoft Visual Studio version 16.8.1, and have enabled these flags in project properties (according to the similar question Standard way of importing modules):

  • /experimental:module
  • /std:c++latest
  • /EHsc
  • /MD

Should I use Clang or GCC instead?

3 Answers

Using the Visual Studio 2019 non preview version:

  1. Create an empty C++ project

  2. Open project properties: Alt + Enter

  3. Go to Configuration Properties → C/C++ → Language, and set the C++ Language Standard option to Preview - Features from the Latest C++

  4. In the same section, set Enable Experimental C++ Standard Library Modules to Yes (/experimental:module)

  5. Go to Configuration Properties → C/C++ → Advanced and set the Compile As option to Compile as C++ Module Internal Partition (/internalPartition)

  6. Add header file to your project, which contains an import declaration for every standard library header you want to import. For example:

    #pragma once
    import <iostream>;
    import <array>;
    import <vector>;
    
  7. Recompile your project

  8. Done, now everything should work fine

The authors stated in the example and solution files provided for download, that due to compilers' implementations of the C++20-standard the files might not work yet (see the book's page for details and corresponding GitHub repository).

Therefore they provide "no modules" examples which use the "#include" directive.

Try to do it like this:

import <iostream>;         // import declaration

Modules help divide large amounts of code into logical parts. Modules are orthogonal to namespaces.

Example:

File helloworld.cpp

export module helloworld;  // module declaration
import <iostream>;         // import declaration

export void hello() {      // export declaration
    std::cout << "Hello, World!\n";
}

File main.cpp

import helloworld;  // import declaration

int main() {
    hello();
}
Related