How to use C++20 modules in CLion

Completed

I build a brand new c++23 project and run the following code below:

// This is hello.ixx
module;
#include <string>
export module hello;

export std::string greet(const std::string& name) {
    return "Hello, " + name + "!";
}
std::string internal_helper() {
    return "I am hidden";
}
// main.cpp
import hello;
#include <iostream>
int main() {
    std::cout << greet("World") << '\n';
    // internal_helper();  // Error
    return 0;
}

CMakeLists.txt gen by CLion automatically:

cmake_minimum_required(VERSION 4.2)
project(test)

set(CMAKE_CXX_STANDARD 23)
add_compile_options(-fmodules-ts)
add_executable(test hello.ixx
        main.cpp)

But I got a bug report in Clion:
D:\CLion2026.1\bin\cmake\win\x64\bin\cmake.exe --build D:\CLion2026.1\PROJECT\test\cmake-build-debug --target test -j 14
[1/3] Building CXX object CMakeFiles/test.dir/hello.ixx.obj
g++.exe: warning: D:/CLion2026.1/PROJECT/test/hello.ixx: linker input file unused because linking not done
[2/3] Building CXX object CMakeFiles/test.dir/main.cpp.obj
FAILED: [code=1] CMakeFiles/test.dir/main.cpp.obj 
D:\CLion2026.1\bin\mingw\bin\g++.exe   -g -std=gnu++23 -fdiagnostics-color=always -fmodules-ts -MD -MT CMakeFiles/test.dir/main.cpp.obj -MF CMakeFiles\test.dir\main.cpp.obj.d -o CMakeFiles/test.dir/main.cpp.obj -c D:/CLion2026.1/PROJECT/test/main.cpp
In module imported at D:/CLion2026.1/PROJECT/test/main.cpp:3:1:
hello: error: failed to read compiled module: No such file or directory
hello: note: compiled module file is 'gcm.cache/hello.gcm'
hello: note: imports must be built before being imported
hello: fatal error: returning to the gate for a mechanical issue
compilation terminated.
ninja: build stopped: subcommand failed.

how to fix it

0
1 comment

Try followin CMakeLists.txt:

cmake_minimum_required(VERSION 4.2)
project(test)

set(CMAKE_CXX_STANDARD 23)

set(CMAKE_CXX_SCAN_FOR_MODULES ON)
set(CMAKE_CXX_EXTENSIONS  ON)

add_executable(test
         main.cpp
)

target_sources(test
        PUBLIC
        FILE_SET modules TYPE CXX_MODULES FILES
        hello.ixx
)

you also need to slightly modify main.cpp

// main.cpp
#include <iostream>
import hello;

int main() {
    std::cout << greet("World") << '\n';
    // internal_helper();  // Error
    return 0;
}

if “#include <iostream>” line is after “import hello” i get 100's of error messages about “parse error in template argument list” and other mysterius stuff. And moving “#include <string>” below “export module hello;” in hello.ixx produces even more errors (here, at least, it's kind of understandable why it doesn't work, but error messages aren't helpfull at diagnosing the problem)

Frankly - this “module” bussines feels more like a hassle than a usefull feature…

 

0

Please sign in to leave a comment.