【问题标题】:How do I define an exported constant?如何定义导出的常量?
【发布时间】: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也不起作用。
  • constconstexpr 都定义了内部链接(即static),如果没有另外指定。如果export 影响到这一点,我找不到任何地方,所以你可能需要类似export extern const int my_constant = 42;
  • @olm 这似乎可以解决问题。将其发布为答案,我会接受它

标签: c++ constants c++20 c++-modules


【解决方案1】:

const 限定变量默认有内部链接,所以可能需要写成

export extern const int my_constant = 42;

根据https://en.cppreference.com/w/cpp/language/storage_duration export 定义应该使变量具有外部链接,因此您可能遇到了 C++20 尚未完全实现的角落之一。

【讨论】:

  • “您可能已经遇到了 C++20 尚未完全实现的问题”我进行了快速搜索,并没有看到针对 g++ 的缺陷。应该有吗?
【解决方案2】:

只需使用inline

export inline constexpr int my_constant = 42;

【讨论】:

  • extern "C++" 的特殊情况之外,模块中不需要内联变量(因为它们不能在多个翻译单元中定义)。
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2018-01-10
  • 2017-03-26
  • 1970-01-01
  • 2019-12-31
  • 2011-02-12
  • 1970-01-01
相关资源
最近更新 更多