c++compilationc++20c++-modules

How do C++ 20 modules resolve same function name problems in different modules?


I'm trying to apply C++ 20 modules to my new project, but currently met with a big problem.

Say I have 3 modules,

  1. mod1.ixx with mod1.cpp
  2. mod2.ixx with mod2.cpp
  3. mod3.ixx with mod3.cpp

and here's their contents

// mod1.ixx
export module mod1;
export int func();

// mod1.cpp
module mod1;
int func() {
  return 1;
} 
// mod2.ixx
export module mod2;
export int func();
export int goo();

// mod2.cpp
module mod2;
int func() {
  return 2;
} 
// mod3.ixx
export module mod3;
export int func3();

// mod3.cpp
module mod3;

import mod1;
import mod2;

int func3() {
  func();
} 

int goo() {
  return 4;
}

Since mod1 and mod2 both export func(), which does func3() exactly call? Does goo in mod3.cpp implement goo 'declared' in mod2.ixx?

I think having & exporting functions of the same name is quite often in real project, how is this handled in C++ 20 modules?

I tried VS2022+msvc, and func3() calls func() in mod1, but I'm not sure if this is the standard.


Solution

  • I think having & exporting functions of the same module is quite often in real project, how is this handled in C++ 20 modules?

    Real projects scope their names in namespaces; that's what the namespace feature is for after all. Modules and namespaces are orthogonal features; neither interferes with the other, but neither requires the other either. Good module practice would be to put all of the stuff in a namespace to avoid this sort of thing.

    As for this case, the standard is pretty clear:

    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

    So it is not allowed, but compilers/linkers don't have to look for it.