m1ss1k
m1ss1k

Reputation: 61

Why does import work with <iostream> but not work with <string> or other libraries?

I'm trying to learn how to work with C++20. I'm using MSVC 19.34.31937 and also set my project in the properties to use C++20. But there is still a problem.

The import statement works "when it wants so". The #include statement works fine.

If I import <iostream>:

import <iostream>; // ok 
import <chrono>; // ok too (the only two libraries that work)

It'll work, but sometimes it won't. But if I import, for example, <string>:

import <string>; // error  C7612: could not find header unit for 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\string'

The most strange thing is that sometimes all std's statements can make a lot of errors. But my question is:

Why does import <iostream> work but import <string> doesn't?

I tried to change the order of importing.

Upvotes: 6

Views: 830

Answers (1)

zerocukor287
zerocukor287

Reputation: 1046

For the record, you need

  1. a compiler that supports modules
  2. a library or project that exports a module

If we stick to MSVC, than we can find here that

As of Visual Studio 2022 version 17.1, C++20 standard modules are fully implemented in the Microsoft C++ compiler.
Before it was specified by the C++20 standard, Microsoft had experimental support for modules. The compiler also supported importing prebuilt Standard Library modules, described below.

Little more search and we can find that the matching compiler for that version of VS is: 19.31

Visual Studio version MSVC version
Visual Studio 2022 version 17.1 1931

Good so far, now we just need to set the proper compiler settings to let it able to use modules:

  • /std:c++latest to enable the latest standard (make sure it is at least /std:c++20)
  • and if we are using a bit older visual studio, add /experimental:module along with /std:c++latest - it will enable standard library modules.

Now, about the second point. We just need a library that exports a module.
If that "string.cpp" would have started with

export module string;

or something similar module export directive, then everything would work properly - as it is working for the VS 17.1 (or newer).

If we are unlucky, we manually need to create a module out of the files we want.
There are a nice question if you can modify the code and another another one if you cannot modify the source.
Basically, you would create a wrapper library, that #include all the files you need, defines a module, and exports what is necessary.

Upvotes: 1

Related Questions