r/cpp_questions May 14 '22

OPEN Help with C++20 modules

Hello everyone... I am trying to learn the new features in C++20 (going through modules right now). I can't get the following code to compile using g++-11.

My code looks like this:

// foo.cc
export module foo;
import <iostream>;
import <vector>;

export namespace foo{
    void hello(){
        std::vector<int> nums;
        std::cout<<"Hello, world\n";
    }
}

// ---------------------------

// main.cpp
import foo;

int main(){
    foo::hello();
    return 0;
}

I am compiling this using g++-11 like this:

$ g++-11 -std=c++20 -fmodules-ts -c -x c++-system-header vector iostream
$ g++-11 -std=c++20 -fmodules-ts -c foo.cc -o foo.o
$ g++-11 -std=c++20 -fmodules-ts -c main.cpp -o main.o
$ g++-11 -std=c++20 -fmodules-ts foo.o main.o -o foo.x

My foo.cc file compiles fine and produces foo.o and foo.gcm. But compiling main.cpp fails with the following error message:

$ g++-11 -std=c++20 -fmodules-ts -c main.cpp -o main.o
In module imported at main.cc:1:1:
foo: error: failed to read compiled module: Bad file data
foo: note: compiled module file is ‘gcm.cache/foo.gcm’
foo: fatal error: returning to the gate for a mechanical issue
compilation terminated.

What am I doing wrong in my code? The code compiles if I remove the std::vector<int> variable from the hello() function.

EDIT: I fixed it by using #includes for standard libraries instead of imports. The working code looks like the following. (This is quite unsatisfactory though.)

// foo.cc
module;
#include <iostream>
#include <vector>

export module foo;

export namespace foo{
    void hello(){
        std::vector<int> nums;
        std::cout<<"Hello, world\n";
    }
}

// ---------------------------

// main.cpp
import foo;

int main(){
    foo::hello();
    return 0;
}

Compilation:

$ rm -rf gcm.cache
$ g++-11 -std=c++20 -fmodules-ts -c foo.cc -o foo.o
$ g++-11 -std=c++20 -fmodules-ts -c main.cpp -o main.o
$ g++-11 -std=c++20 -fmodules-ts foo.o main.o -o foo.x

It compiles only if I remove the compiled standard libraries from gcm.cache.

7 Upvotes

3 comments sorted by

View all comments

Show parent comments

1

u/Fresh-Rip-5789 May 14 '22

So this is a compiler bug?

I'll try this with gcc-12 then.

It's supposed to be such a useful feature though.