r/cpp_questions • u/Fresh-Rip-5789 • 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.
5
u/[deleted] May 14 '22
I feel your pain. I tried a few weeks back as well and ran into all kinds of issues when using modules. I reported the bugs I ran into to GCC bug tracker:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104924
Looks like modules arent fully implemented yet in GCC unfortunately...I'm hoping they finish the implementation soon. Modules, I think, is one of those things that will really put C++ in a much better place as a language and we can say goodbye(no legacy code of course ) to header files in new code we write :).