我一直在尝试新的模块功能,但无法导出全局常量。导出似乎编译得很好,但是在导入时编译器抱怨未声明常量。我的代码:
test.cpp
export module test;
export struct my_type { int x, y; };
export constexpr int my_constant = 42;
export int my_function() { return my_constant; }
main.cpp
import test;
int main() {
my_type t{1, 2};
int i = my_function();
int j = my_constant; // <- error here
}
我究竟做错了什么?我在 Linux 上使用 g++ 11.1.0:g++-11 -std=c++20 -fmodules-ts test.cpp main.cpp -o main
错误信息是:error: ‘my_constant’ was not declared in this scope
const 限定的变量默认具有内部链接,因此可能需要将其写为
export extern const int my_constant = 42;
根据https://en.cppreference.com/w/cpp/language/storage_duration the export
定义应该使变量具有外部链接,因此您可能遇到了 C++20 尚未完全实现的角落之一。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)