dwto
dwto

Reputation: 795

C++ Modules: Best practice for importing standard library

I'm trying to understand the difference between two inclusions of standard headers in C++20 in Modules world. The flowing are the two options:

1.

export module my_module;
import <iostream>;

export void do_something() { 
   std::cout << "hello";
}
module;

#include <iostream>;

export module my_module;

export void do_something() { 
   std::cout << "hello";
}

I think in this case 1 and 2 are identical, but perhaps 1 is considered superior since if I add other #includes before #include <iostream> in option 2, such includes that define macros may change the behavior of <iostream>. While introducing a global module fragment in option 1 and adding include will not change the behaviour of import <iostream>. Am I right?

For completeness, in C++23 I would do:

export module my_module;
import std;

export void do_something() { 
   std::cout << "hello";
}

Upvotes: 1

Views: 651

Answers (1)

Chukwujiobi Canon
Chukwujiobi Canon

Reputation: 4067

You can import a standard library module if your implementation provides a standard library module else you’ve got to #include the good ol header files and let the preprocessor do what it has been doing best since PL/1 and Algo —pun intended.

Is it best practice to use C++20 modules? Of course! Faster compilation times? You bet. But you cannot completely go without header files. At least not anytime soon…

assert() is a macro and so far we haven’t agreed on a non-macro replacement for it.

The first illustration:

export module my_module;
import <iostream>;

export void do_something() { 
   std::cout << "hello";
}

Will compile iff the implementation provides standard library modules. Else, fallback to the second illustration:

module;
#include <iostream>;
export module my_module;

export void do_something() { 
   std::cout << "hello";
}

Obligatory nitpicking: Do not import the std module if you want to ensure that standard-library facilities not suitable in a context aren’t deliberately or accidentally imported.

export module my_module;
import std;

export void do_something() { 
   std::cout << "hello";
}

Upvotes: 1

Related Questions