如何定义导出的常量?

问题描述

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

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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...