如何定义导出的常量
How do I define an exported constant?
我一直在尝试新的模块功能,但无法导出全局常量。导出似乎编译得很好,但当导入时,编译器会抱怨没有声明常量。我的代码:
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;
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我可以在运行时重新定义在 OpenCascade/OCCT 标头中定义的 c++ 静态常量吗?
- 在定义的函数中使用常量时出错
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- C++ 确保子类为常量提供自定义值
- 用矩阵将函数中的整数值替换定义的常量
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 将字符串文本常量定义为 char const* 和 wchar const*
- 为什么不建议使用宏符号常量定义一个固定长度的数组呢
- 我可以使用常量定义数组的长度,那么为什么 int d[b] 不起作用呢?
- 调用构造函数与将内联常量定义为默认参数
- 是否允许在常量定义的对象上丢弃 const 只要它没有实际被修改?
- 多个文件中的常量定义
- 常量定义和模板
- 如何在另一个命名空间中使用常量定义的外部
- 全局常量定义的顺序
- 将常量定义为函数会导致标头=坏主意
- 是一个宏,其变量总是用变量或常量定义