首页 > 解决方案 > 错误:无法读取已编译的模块:没有这样的文件或目录

问题描述

我刚刚购买了《Beginning C++20》(电子书版)一书,我正在尝试使用新的 C++20 方法编译第一个示例。

源文件的内容是

// Ex1_01.cpp
// A Complete C++ program
import <iostream>;

int main()
{
    int answer{42};     // Defines answer with 42
    std::cout << "The answer to life, the universe, and everything is "
        << answer
        << std::endl;
    return 0;
}

如果我理解正确的话,GCC 版本 10 或 11 尚不支持此功能(一些网站声称 GCC 11 支持它,但是当我使用 -fmodules-ts 标志时,正如一些人所暗示的那样,有一条错误消息表明它未实现/实验性和退出。

经过一番搜索,我发现了一些引用https://gcc.gnu.org/wiki/cxx-modules的帖子,其中有安装支持模块的 GCC 10 版本的说明(使用 -fmodules-ts 标志)但是当我在我的示例代码中使用它时,我收到以下错误:

In module imported at Ex1_01.cpp:3:1:
/usr/local/include/c++/10.0.0/iostream: error: failed to read compiled module: No such file or directory
/usr/local/include/c++/10.0.0/iostream: note: compiled module file is ‘gcm.cache/./usr/local/include/c++/10.0.0/iostream.gcm’
/usr/local/include/c++/10.0.0/iostream: fatal error: jumping off the crazy train to crashville
compilation terminated.

gcc 的版本是:g++ (GCC) 10.0.0 20200110 (experimental) [svn-280157:20201220-1704] 我在 Stack Overflow 上找到了一个帖子,其中有人指向这个版本(如何使用 modules-ts 编译 C++ 代码和 gcc(实验性)?

我还尝试了 wiki 中的示例(hello.cc 和 main.cc),但这些示例也给出了错误消息:

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: fatal error: jumping off the crazy train to crashville
compilation terminated.

有没有办法使这项工作,或者我应该从“旧”#include 方法开始,直到有支持模块的 GCC 11 的稳定版本?据我了解,如果我构建 GCC 11 的最新快照,大多数其他 C++20 特定代码应该可以工作吗?(或者只是坚持我的发行版提供的默认 (g++ (Debian 10.2.1-1) 10.2.1 20201207) 版本?)

标签: c++gccmoduleg++c++20

解决方案


我想我会回答我自己的问题。

当我按照 GCC wiki ( https://gcc.gnu.org/wiki/cxx-modules ) 上的说明进行操作时,与 svn 上的版本相比,它是一个更新的版本。

svn 的 gcc 版本为 10,而 github 的版本为 11。

当我为 github (g++ (GCC) 11.0.0 20201217 (experimental) [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";
}

和 main.cpp

import hello;
int main (void)
{
  greeter ("world");
  return 0;
}

编译命令为:g++ -fmodules-ts hello.cpp main.cpp

据我了解,源文件的顺序很重要,因此需要在 main.cpp 之前编译 hello.cpp

所以目前似乎只有用户制作的模块可以工作,而不是标准库的模块(因为仍然需要#include)。

[编辑] 似乎模块支持现在与 gcc-11 的主分支合并,因此不再需要通过 git 或 svn 使用开发人员构建(不幸的是,标准库头文件还没有转换为模块,所以在时刻导入;不起作用)。


推荐阅读