我正在尝试运行一个简单的程序:
import <iostream>;
int main()
{
std::cout << "Hello, World!" << std::endl;
return 0;
}
我已经检查过了,据说我已经有了最新版本的 gcc。build-essential 已经是最新版本 (12.9ubuntu3)。
我尝试过跑步:
g++ -std=gnu++20 -o hello hello.cpp
或者
gcc -std=c++20 -o hello hello.cpp
但他们都给了我
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
1 | import <iostream>;
| ^~~~~~~~
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:9: error: ‘iostream’ was not declared in this scope
hello.cpp:1:1: error: ‘import’ does not name a type
1 | import <iostream>;
| ^~~~~~
hello.cpp:1:1: note: C++20 ‘import’ only available with ‘-fmodules-ts’, which is not yet enabled with ‘-std=c++20’
hello.cpp: In function ‘int main()’:
hello.cpp:4:6: error: ‘cout’ is not a member of ‘std’
4 | std::cout << "Hello, World!" << std::endl;
| ^~~~
hello.cpp:1:1: note: ‘std::cout’ is defined in header ‘<iostream>’; did you forget to ‘#include <iostream>’?
+++ |+#include <iostream>
1 | import <iostream>;
hello.cpp:4:38: error: ‘endl’ is not a member of ‘std’
4 | std::cout << "Hello, World!" << std::endl;
| ^~~~
hello.cpp:1:1: note: ‘std::endl’ is defined in header ‘<ostream>’; did you forget to ‘#include <ostream>’?
+++ |+#include <ostream>
1 | import <iostream>;
然后我运行:gcc -std=c++20 -fmodules-ts hello.cpp
现在我明白了
In module imported at hello.cpp:1:1:
/usr/include/c++/11/iostream: error: failed to read compiled module: No such file or directory
/usr/include/c++/11/iostream: note: compiled module file is ‘gcm.cache/./usr/include/c++/11/iostream.gcm’
/usr/include/c++/11/iostream: note: imports must be built before being imported
/usr/include/c++/11/iostream: fatal error: returning to the gate for a mechanical issue
compilation terminated.
我目前被困在这里......
答案1
截至本文发布之日,g++ 中的模块支持尚不完整。特别是,
标准库头文件单元
标准库不提供可导入的头文件单元。如果要导入此类单元,必须先显式构建它们。如果不小心执行此操作,则可能会有多个声明,模块机制必须合并这些声明 — 编译器资源使用情况可能会受到将头文件划分为头文件单元的方式的影响。
您可以使用以下方式构建 iostream 模块
g++ -std=c++20 -fmodules-ts -xc++-system-header iostream
gcm.cache
这将在当前目录中创建一个目录,其内容如下
$ tree gcm.cache/
gcm.cache/
└── usr
└── include
└── c++
└── 11
└── iostream.gcm
4 directories, 1 file
(我使用的是 Ubuntu 22.04 附带的默认 gcc/g++ 11.2.0-19ubuntu1)。
然后您可以hello.cpp
使用-fmodules-ts
编译器标志来构建您的:
$ g++ -std=gnu++20 -fmodules-ts -o hello hello.cpp
$
$ ./hello
Hello, World!
参考: