c++c++20c++-modulesvisual-c++-2022

Visual Studio 2022 C++ Modules compiler bug?


I am trying to learn how modules work in C++20 and created a simple hello world example in Visual Studio 2022 Community (Version 17.5.3)

hello1.ixx:

export module hello1;

import <iostream>;

export void hello() {
  std::cout << "Hello, world from hello1\n";
}

hello2.ixx:

export module hello2;

import <iostream>;

export void hello() {
  std::cout << "Hello, world from hello2\n";
}

main.cpp

import hello1;
import hello2;

int main() {
  hello();
  return 0;
}

This program compiles just fine and when run I get this output:

Hello, world from hello1

And if I change the order of the imports:

import hello2;
import hello1;

I get output:

Hello, world from hello2

Afaik the order of imports should not matter, and this program should fail compilation since there are two definitions of the hello() function and the call to it is ambiguous.

Is this a compiler bug?


Solution

  • This code is ill-formed, no diagnostic required. Per [basic.link]/9:

    If multiple declarations of the same name with external linkage would declare the same entity except that they are attached to different modules, the program is ill-formed; no diagnostic is required.

    Having no diagnostic be required means that compilers don't have to detect this circumstance. Your code is still broken, but compilers are not required to do what would be necessary to detect this breakage.

    Exported names have external linkage. Therefore, this passage applies. You should do what you reasonably can to avoid this by using proper namespace scoping for code exported by a module.