Search code examples
c++visual-studiovisual-c++c++20c++-modules

Import std header unit in module implementation file


I'm running on VS2022 17.10.1 (latest) with MSVC and C++20:

This is my module iface - hello.iface.ixx :

export module hello;

export void hi();

And this is its impl - hello.impl.cpp:

module hello;
import <iostream>;

void hi() {
    std::cout << "hi";
}

It does not compile due to this line:

import <iostream>;

There are a few ways to solve it but I'm unsure which one is proper.

  1. If I change hello.impl.cpp file to .ixx or Compile As: /interface it works. It looks like header unit import is only accepted in an interface file. What are the implications? two BMI's are created? I read that I better stick with .cpp files for module implementation files.

  2. If I add the import <iostream>; to hello.iface.ixx it works. But it seems to me like bad practice to reveal that I'm using on iface. As only impl uses cout.

  3. I can use global module fragment in hello.impl.cpp. But I think the #include <iostream> might be less efficient than the supported import <iostream>; in the two options above.

I will mention that it works as is with Preview /std:c++latest


Solution

  • In project's properties -> C++ -> scan source for Module Dependencies: Yes.