Practical Development of Import in C++23

Practical Development of Import in C++23

1. Introduction to Modules

The import module application mechanism was introduced in C++20. However, due to the lag in compilers and environments, it is unlikely to be widely adopted in the short term. This does not mean that developers can ignore it; the emergence of a new technology, regardless of the final outcome, requires practical application and feedback. So how can we use this mechanism in actual programming? Below, I will demonstrate with a very simple program to help everyone gradually accept it.The development environment used is Ubuntu 25.10, with the default version of GCC being 15.2, and the default C++ standard set to C++20. If any related libraries or compilation environment limitations are encountered, please install them as prompted; further details will not be elaborated here.

2. A Very Simple Program

As usual, let’s start with the simplest program:

import std;
int main(){
    std::println("this is first test!");
    std::cout<<"test"<<std::endl;
    return 0;
}

This program is very simple, but if we use traditional compilation methods as shown below:

g++ -o test importDemo.cpp

It will produce the following error:

error: 'import' does not name a type

This indicates that traditional compilation methods currently cannot satisfy the requirements for using module compilation.

3. Compilation and Processing

So how can we correctly compile the above code? We can try using the following compilation command:

g++ -o test importDemo.cpp -std=c++23 -fmodules

However, it will report the following issue:

g++ -o test importDemo.cpp -std=c++23 -fmodules
In module imported at importDemo.cpp:1:1:
std: error: failed to read compiled module: No such file or directory
std: note: compiled module file is ‘gcm.cache/std.gcm’
std: note: imports must be built before being imported
std: fatal error: returning to the gate for a mechanical issue
compilation terminated.

From the above compilation results, we find that the file “gcm.cache/std.gcm” is missing. How can we obtain this file? After researching, we found that it needs to be compiled in advance:

g++ -std=c++23 -fmodules-ts -fsearch-include-path -c bits/std.cc

After executing this command, we can find the mentioned file and a std.o file in the current directory. Now, using “g++ -o test importDemo.cpp -std=c++23 -fmodules” will correctly compile the program. Then executing the compiled program will print the content of the program.

4. Conclusion

Through this very simple introductory compilation application, everyone can clearly understand how to compile after introducing modules. With this simple example, you can step into the world of C++ module development and start learning and improving your skills freely according to your own wishes.

Leave a Comment