C++20 Modules with CLion and CMake
cxx
Iāve been working through Crafting Interpreters in C++20, so I tried out using the new modules. There were a couple of unintuitive things with using modules with CLion and CMake, so Iāll document them here so that it may help future me (and maybe other people too).
Skip to finished CMakeLists.txt
Creating a module
Create a CLion C++ Executable project with language standard C++ 20.
Create a new module by selecting New -> C++ Module Interface Unit. Give it a name, and leave āAdd to targetsā checked.
Then, fill out your module:
Import your module from main.cpp
and use it:
When you run the executable, youāll see that the build errors! Youāll get a message like:
Even though we had CLion add our file to the CMake build target, CMake isnāt satisfied. Because we created a module interface unit (a file that exports a module), weāll need to add it to a special file set.
A modules file set
Here is what our projectās CMakeLists.txt has by default:
Underneath that, add a file set of type CXX_MODULES
and add the module interface unit (carrot.ixx
) to it:
Run the executable again, and the build should succeed.
Creating a file glob for module interface units
This configuration allowed us to add one module interface unit to our build, but each time we create a new one, weāll need to manually add it, which would get annoying.
To resolve this, we can create a file glob for module interface units:
With this, we can replace the hard-coded list of files with the file glob:
Finished CMakeLists.txt
Here is what my finished CMakeLists.txt looks like (Iāve added an apple.ixx
module to verify that it works):