如何在 GCC 中使用 c 20 模块?

新手上路,请多包涵

我目前正在使用 GCC 10.1.0 尝试使用 此处 描述的称为 模块 的新 C++20 功能,但是如果我尝试构建以下代码片段,编译器会给我带来一堆错误。

这是我到目前为止写的片段:

 // helloworld.cpp
export module helloworld;  // module declaration
import <iostream>;         // import declaration

export void hello() {      // export declaration
    std::cout << "Hello world!\n";
}

 // main.cpp
import helloworld;  // import declaration

int main() {
    hello();
}

我正在使用 g++ helloworld.cpp main.cpp -std=c++20 编译它。

编译器给了我这个错误:

 helloworld.cpp:2:1: warning: keyword ‘export’ not implemented, and will be ignored
    2 | export module helloworld;  // module declaration
      | ^~~~~~
helloworld.cpp:2:8: error: ‘module’ does not name a type
    2 | export module helloworld;  // module declaration
      |        ^~~~~~
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
    3 | import <iostream>;         // import declaration
      |         ^~~~~~~~
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:9: error: ‘iostream’ was not declared in this scope
helloworld.cpp:3:1: error: ‘import’ does not name a type
    3 | import <iostream>;         // import declaration
      | ^~~~~~
helloworld.cpp:5:1: warning: keyword ‘export’ not implemented, and will be ignored
    5 | export void hello() {      // export declaration
      | ^~~~~~
helloworld.cpp: In function ‘void hello()’:
helloworld.cpp:6:10: error: ‘cout’ is not a member of ‘std’
    6 |     std::cout << "Hello world!\n";
      |          ^~~~
helloworld.cpp:1:1: note: ‘std::cout’ is defined in header ‘<iostream>’; did you forget to ‘#include <iostream>’?
  +++ |+#include <iostream>
    1 | // helloworld.cpp
main.cpp:2:1: error: ‘import’ does not name a type
    2 | import helloworld;  // import declaration
      | ^~~~~~
main.cpp: In function ‘int main()’:
main.cpp:5:5: error: ‘hello’ was not declared in this scope
    5 |     hello();
      |     ^~~~~

我做错了什么?

原文由 beep 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

GCC 的语言状态页面 说它还不支持模块。

C++20 支持还不完整(考虑到我们 2020 年,这已经足够公平了!而且 C++20 在技术上还不存在……)。

然而,通过一些标志和一个开发分支,您可以使用正在进行的实现——在 GCC 的 Modules Wiki 上阅读更多关于它的信息。

GCC 10 中的默认语言版本是 C++14; GCC 11 将其提升到 C++17。

原文由 Asteroids With Wings 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题