如何在c++20中使用g++中的模块?

2022-05-17 00:00:00 g++ c++ c++20 c++-modules

我阅读了此链接https://gcc.gnu.org/wiki/cxx-modules,并尝试从此网站复制以下示例。我已经知道这个编译器部分支持模块系统。(注意:我使用的是Windows)

// hello.cc
module;
#include <iostream>
#include <string_view>
export module hello;
export void greeter(std::string_view const &name) {
  std::cout << "Hello " << name << "!
";
}
// main.cc
import hello;
int main() {
  greeter("world");
  return 0;
}
// Should print "Hello world!" 

我当前有GCC 11.0.1快照,并尝试使用以下参数编译这些文件: g++ -std=gnu++2b -Wall -fmodules-ts hello.cc main.cc编译器给了我以下错误:

hello.cc:6:8: internal compiler error: in get_cxx_dialect_name, at cp/name-lookup.c:7027
    6 | export module hello;
      |        ^~~~~~
libbacktrace could not find executable to open
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://gcc.gnu.org/bugs/> for instructions.
In module imported at main.cc:1:1:
hello: error: failed to read compiled module: No such file or directory
hello: note: compiled module file is 'gcm.cache/hello.gcm'
hello: note: imports must be built before being imported
hello: fatal error: returning to the gate for a mechanical issue
compilation terminated.

如果我先编译hello.cc,则编译器仍给出错误:

C:...hello.cc | 6 | error: failed to write compiled module: No such file or directory |
C:...hello.cc | 6 | note: compiled module file is 'gcm.cache/hello.gcm' |
  • 我应该做什么?
  • 我是否应该等待g++对模块的完全支持?
  • 即使g++部分支持它,是否还有其他使用方法?

解决方案

升级现有项目时遇到类似问题。该问题与文件扩展名有关,请确保已将编译单元命名为hello.cpp

bcrowhurst@pop-os:/tmp$ g++ -fmodules-ts hello.mpp main.cpp
In module imported at main.cpp:1:1:
hello: error: failed to read compiled module: No such file or directory
hello: note: compiled module file is ‘gcm.cache/hello.gcm’
hello: note: imports must be built before being imported
hello: fatal error: returning to the gate for a mechanical issue
compilation terminated.
bcrowhurst@pop-os:/tmp$ mv hello.mpp hello.cpp
bcrowhurst@pop-os:/tmp$ g++ -fmodules-ts hello.cpp main.cpp
bcrowhurst@pop-os:/tmp$ ./a.out
Hello world!

此外,尝试将文件重命名回hello.mpp以查看原始错误时遇到问题;删除gcm.cache/文件夹已修复该问题。

bcrowhurst@pop-os:/tmp$ mv hello.cpp hello.mpp
bcrowhurst@pop-os:/tmp$ g++ -fmodules-ts hello.mpp main.cpp
/usr/bin/ld:hello.mpp: file format not recognized; treating as linker script
/usr/bin/ld:hello.mpp:1: syntax error
collect2: error: ld returned 1 exit status
bcrowhurst@pop-os:/tmp$ rm -rf gcm.cache
bcrowhurst@pop-os:/tmp$ g++ -fmodules-ts hello.cpp main.cpp
bcrowhurst@pop-os:/tmp$ ./a.out
Hello world!

似乎g++-11.1有一个限制(通过设计?)在扫描模块编译单元时。这与C++20规范本身无关。

链接

https://en.cppreference.com/w/cpp/language/modules

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4720.pdf

相关文章