C++ 如何定义导出的常量?

C++ 如何定义导出的常量?,c++,constants,c++20,c++-modules,C++,Constants,C++20,C++ Modules,我一直在尝试新的模块功能,但无法导出全局常量。导出似乎编译得很好,但在导入时编译器会抱怨没有声明常量。我的代码: 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() {

我一直在尝试新的模块功能,但无法导出全局常量。导出似乎编译得很好,但在导入时编译器会抱怨没有声明常量。我的代码:

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
}
导入测试;
int main(){
my_型t{1,2};
int i=我的函数();

int j=my_constant;//const限定变量默认具有内部链接,因此可能需要将其写入

export extern const int my_constant = 42;

根据导出定义,应该使变量具有外部链接,因此您可能遇到了C++20尚未完全实现的一个问题。

const限定变量默认具有内部链接,因此可能需要将其编写为

export extern const int my_constant = 42;

根据
导出
定义,应该使变量具有外部链接,因此您可能遇到了C++20尚未完全实现的一个角落。

只需使用
内联

export inline constexpr int my_constant = 42;

只需使用
inline

export inline constexpr int my_constant = 42;

你能试着像导出
const
一样导出它吗?我想知道模块和
constepr
是否还不是很好。@rturrado除了
const
之外也不起作用。
const
constepr
都定义了内部链接(即
static
)如果没有另外指定。如果
export
影响到这一点,我找不到任何地方,因此您可能需要类似于
export extern const int my_constant=42;
@olm的东西。这似乎可以解决问题。将其作为答案发布,我会接受它。您可以尝试将其导出为
const
?我想知道模块和
constepr
还不是很好。@rturrado除了
const
之外也不起作用。
const
constepr
都定义了内部链接(即
静态
)如果没有另外指定。如果
导出
影响到这一点,我找不到任何地方,因此您可能需要像
导出外部常量int my_constant=42;
@olm这样的东西。这似乎可以解决问题。将其作为答案发布,我将接受非常特殊的
外部“C++”案例的外部
,模块中永远不需要内联变量(因为它们不能在多个翻译单元中定义)。除了非常特殊的
外部“C++”
,模块中永远不需要内联变量(因为它们不能在多个翻译单元中定义)。