全局.cpp
module;
#include "global.hpp"
export module global;
export template <typename T> void output(T item) { dump(item); }
全局.hpp
#include <iostream>
template <typename T> void dump(T val) { std::cout << val << std::endl; }
主.cpp
import global;
int main() { output(42); }
我编译它:
g++ -fmodules-ts global.cpp main.cpp
输出:
In file included from /usr/include/c++/11/iostream:39,
from global.hpp:13,
from global.cpp:15,
of module global, imported at main.cpp:13:
/usr/include/c++/11/ostream: In instantiation of ‘std::basic_ostream@global<_CharT, _Traits>& std::endl@global(std::basic_ostream@global<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits@global<char>]’:
global.hpp:15:59: required from ‘void dump@global(T) [with T = int]’
global.cpp:19:56: required from ‘void output@global(T) [with T = int]’
main.cpp:15:20: required from here
/usr/include/c++/11/ostream:685:19: error: ‘flush’ was not declared in this scope
685 | { return flush(__os.put(__os.widen('\n'))); }
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
但这是废话,因为当我编译以下代码时,一切正常,编译正常:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
}
g++ 有什么问题,我应该如何编译才能一切正常?
您必须先将
iostream
库编译为模块,然后才能编译所需的程序。
因此,删除缓存然后运行:
g++ -std=c++20 -fmodules-ts -x c++-system-header iostream
之后,您可以按照问题中的方式编译您的程序。另外,在编译
iostream
库时,不要忘记指定 c++ 版本。