import <iostream>;
main(){
std::cout<<"测试"<<std::end;
}
需要保证gcc版本大于10可通过gcc -v查看版本
gcc -v
出现error: ‘import’ does not name a type
1 | import <iostream>;
| ^~~~~~
需要添加-std=c++20(使用C++20) -fmodules-ts(使用模块功能)
g++ -std=c++20 -fmodules-ts test.cpp -o test
错误表示没有找到模块文件,需要先将标准库头文件iostream导出成模块文件
/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.
运行 g++ -std=c++20 -fmodules-ts -x c++-system-header iostream会在当前文件夹生成 gcm.cache文件夹包含模块iostream.gcm,之后不需要任何操作gcc自动识别
g++ -std=c++20 -fmodules-ts -x c++-system-header iostream
重新编译 g++ -std=c++20 -fmodules-ts test.cpp -o test生成可执行文件test
g++ -std=c++20 -fmodules-ts test.cpp -o test
./test