如何定义导出的常量

How do I define an exported constant?

本文关键字:常量 定义 何定义      更新时间:2024-09-22

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

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_durationexport的定义应该使变量具有外部链接,因此您可能遇到了C++20尚未完全实现的问题之一。

只需使用inline

export inline constexpr int my_constant = 42;