c++c++20clang++c++-modules

How do you import one C++20 module into another C++ Module when using clang++?


I have the following two modules:

module_a.cppm:

export module module_a;

export namespace A_Namespace{
  const int A_Export = 2;
}

module_b.cppm:

export module module_b;

import module_a;

export namespace B_Namespace
{
    const int B_Export = A_Namespace::A_Export + 1;
}

I want to compile these modules into .pcm files for use in an executable. To do so, I use the following commands:

clang++ -fmodules-ts --precompile module_a.cppm -o module_a.pcm
clang++ -fmodules-ts --precompile module_b.cppm -o module_b.pcm

And then module_a.pcm and module_b.pcm would get compiled into .o files, which are then compiled into my final executable.

The module_a.pcm file compiles successfully, however module_b.pcm outputs the following error:

fatal error: module 'module_a' not found

I suspect that this is because the definition for module_a is not provided when compiling module_b. Were I using the traditional .hpp/.cpp combination, I would compile the sources for module_a.cpp and module_b.cpp into a single binary, and the header files module_a.hpp and module_b.hpp would provide a declaration that the compiler can satisfy.

How do you satisfy module-interdependencies during compilation?

The above was produced using clang++ 14.0.0 on an x64 Ubuntu 22.04 instance


Solution

  • Modules can not import other modules, only system libraries (e.g import <iostream>;).

    This functionality is supported by C++ as module partitions.

    I've included a partition example:

    module_a.cppm:

    export module MyModule;
    
    export namespace A_Namespace{
      const int A_Export = 2;
    }
    

    module_b.cppm:

    export module MyModule:b;
    
    export namespace B_Namespace
    {
        const int B_Export = A_Namespace::A_Export + 1;
    }
    

    However clang v14 does not yet support the syntax:

    module_b.cppm:1:23: error: sorry, module partitions are not yet supported

    It is documented as supported in Clang v15.