我刚刚购买了《Beginning C++20》(电子书版本)一书,并且正在尝试使用新的 C++20 方法编译第一个示例。
\n源文件的内容是
\n// Ex1_01.cpp\n// A Complete C++ program\nimport <iostream>;\n\nint main()\n{\n int answer{42}; // Defines answer with 42\n std::cout << "The answer to life, the universe, and everything is "\n << answer\n << std::endl;\n return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n如果我理解正确的话,GCC 版本 10 或 11 尚不支持这一点(一些网站声称 GCC 11 支持它,但是当我按照某些建议使用 -fmodules-ts 标志时,会出现一条错误消息,表明它尚未实现/实验并退出。
\n经过一番搜索后,我发现了一些参考https://gcc.gnu.org/wiki/cxx-modules的帖子,其中有安装支持模块的 GCC 10 版本的说明(使用 -fmodules-ts 标志) )但是当我在示例代码中使用它时,我收到以下错误:
\nIn module imported at Ex1_01.cpp:3:1:\n/usr/local/include/c++/10.0.0/iostream: error: failed to read compiled module: No such file or directory\n/usr/local/include/c++/10.0.0/iostream: note: compiled module file is \xe2\x80\x98gcm.cache/./usr/local/include/c++/10.0.0/iostream.gcm\xe2\x80\x99\n/usr/local/include/c++/10.0.0/iostream: fatal error: jumping off the crazy train to crashville\ncompilation terminated.\n
Run Code Online (Sandbox Code Playgroud)\ngcc 的版本是:\ng++ (GCC) 10.0.0 20200110 (experimental) [svn-280157:20201220-1704]\n我在 Stack Overflow 上找到了一篇文章,其中有人指出了这个版本(How to compile C++ code usingmodules) -ts 和 gcc(实验)?)
\n我还尝试了 wiki 中的示例(hello.cc 和 main.cc),但它们也给出了错误消息:
\nIn module imported at main.cpp:1:1:\nhello: error: failed to read compiled module: No such file or directory\nhello: note: compiled module file is \xe2\x80\x98gcm.cache/hello.gcm\xe2\x80\x99\nhello: fatal error: jumping off the crazy train to crashville\ncompilation terminated.\n
Run Code Online (Sandbox Code Playgroud)\n有没有办法做到这一点,或者我应该从“旧”#include 方法开始,直到有支持模块的稳定版本的 GCC 11 为止?据我所知,如果我构建 GCC 11 的最新快照,大多数其他 C++20 特定代码应该可以工作吗?(或者只是坚持使用我的发行版提供的默认 (g++ (Debian 10.2.1-1) 10.2.1 20201207) 版本?)
\n小智 7
我想我会回答我自己的问题。
当我按照 GCC wiki ( https://gcc.gnu.org/wiki/cxx-modules ) 上的说明进行操作时与 svn 上找到的版本相比,这是一个更新的版本。
svn 的 gcc 版本为 10,而 github 的 gcc 版本为 11。
当我编译 github 版本(g++ (GCC) 11.0.0 20201217(实验)[c++-modules revision 20201220-2203])时,GCC Wiki 提供的示例进行编译和工作。这些文件是 hello.cpp:
module;
#include <iostream>
#include <string_view>
export module hello;
export void greeter (std::string_view const &name)
{
std::cout << "Hello " << name << "!\n";
}
Run Code Online (Sandbox Code Playgroud)
和主.cpp
import hello;
int main (void)
{
greeter ("world");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译命令为:g++ -fmodules-ts hello.cpp main.cpp
据我了解,源文件的顺序很重要,因此 hello.cpp 需要在 main.cpp 之前编译
所以目前看来只有用户制作的模块可以工作,而标准库的模块则不能工作(对于那些#include 仍然是必需的)。
[编辑] 似乎模块支持现在已与 gcc-11 的主分支合并,因此不再需要通过 git 或 svn 使用开发人员构建(不幸的是,标准库标头尚未转换为模块,因此在瞬间导入;不起作用)。