Screenshot

A coworker shared the Stroustrup paper titled “21st Century C++”. I was reading a PDF version, but a search turns up an online version too.

This paper included use of C++ with modules. I’ve had my eyes on those since working on DB2, which suffered from include file hell (DB2’s include file hierarchy was a fully connected graph). However, until today, I didn’t realize that there were non-experimental compilers that included module support.

Here’s a sample program that uses modules (Stroustrup’s, with a main added)

import std;

using namespace std;

vector<string> collect_lines(istream &is) {
  unordered_set<string> s;
  for (string line; getline(is, line);)
    s.insert(line);

  return vector{from_range, s};
}

int main() {
  auto v = collect_lines(cin);
  for (const auto &i : v) {
    cout << format("{}\n", i);
  }

  return 0;
}

A first attempt to compile this, even with -std=c++23 bombs:

fedoravm:/home/peeter/physicsplay/programming/module> g++ -std=c++23 -o try try.cc 2>&1 | head -5
try.cc:1:1: error: ‘import’ does not name a type
    1 | import std;
      | ^~~~~~
try.cc:1:1: note: C++20 ‘import’ only available with ‘-fmodules’, which is not yet enabled with ‘-std=c++20’
try.cc:5:8: error: ‘string’ was not declared in this scope

but we get a hint about what is needed (-fmodules). However, that’s not enough by itself:

fedoravm:/home/peeter/physicsplay/programming/module> g++ -std=c++23 -fmodules -o try try.cc 2>&1 | head -5
In module imported at try.cc: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

Here’s the magic sequence that we need, which includes a build of the C++ std export too:

g++ -std=c++23 -fmodules -c /usr/include/c++/15/bits/std.cc
g++ -std=c++23 -fmodules   -c -o try.o try.cc
g++ -std=c++23 -fmodules -o try std.o try.o  

On this VM, I have g++-15 installed, which is sufficient to build and run this little program, modules and all.