c++cmakec++20c++-modules

How to specify C++-module-implementation file in CMakeLists.txt?


I want to create a c++-20-module without partitions but where the interface is in a different file than the implementation. This is my setup:

interface file ModuleTest.ixx:

export module moduleTest;
export int foo();

implementation file ModuleTest.cpp:

module moduleTest;
int foo() {
  // some implementation
}

How do I need to specify the implementation file within the corresponding target in CMakeLists.txt?

This is what I tried:

add_library(moduleTest)

target_sources(moduleTest
    PRIVATE FILE_SET CXX_MODULES FILES
    ModuleTest.ixx
    PRIVATE
    ModuleTest.cpp
)
target_compile_features(moduleTest PUBLIC cxx_std_20)
target_compile_options(moduleTest PRIVATE "-fmodules-ts")

Error message:

moduleTest: error: failed to read compiled module: No such file or directory
moduleTest: note: compiled module file is 'gcm.cache/moduleTest.gcm'
moduleTest: note: imports must be built before being imported
moduleTest: fatal error: returning to the gate for a mechanical issue

If the last line of the CMakeLists.txt is missing, the compiler does not recognize module in ModuleTest.cpp as a keyword. If I move ModuleTest.cpp to the FILE_SET next to ModuleTest.ixx in CMakeLists.txt, cmake complains:

ModuleTest.cpp.o is of type CXX_MODULES but does not provide a module interface unit or partition.

gcc version: 14.2

CMake version: 3.31.7 with ninja generator


Solution

  • It turned out that the problem was the statement

    cmake_minimum_required(VERSION 3.20)
    

    in a parent CMakeLists.txt file. It seems to set some cmake policy to an old value which lead to the error, even though the cmake version I used was more recent. Using

    cmake_minimum_required(VERSION 3.28.2)
    

    solved the problem, despite the fact that the cmake version did not actually change.