【发布时间】:2023-04-01 19:04:01
【问题描述】:
我一直在尝试新的模块功能,但无法导出全局常量。导出似乎编译得很好,但是在导入编译器时抱怨没有声明常量。我的代码:
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吗?我想知道模块和constexpr是不是相处得还不是很好。 -
@rturrado 除了
const也不起作用。 -
const和constexpr都定义了内部链接(即static),如果没有另外指定。如果export影响到这一点,我找不到任何地方,所以你可能需要类似export extern const int my_constant = 42; -
@olm 这似乎可以解决问题。将其发布为答案,我会接受它
标签: c++ constants c++20 c++-modules