How do I define an exported constant?

Viewed 760

I've been trying the new modules feature, but I'm unable to export a global constant. The exporting seems to compile fine, but when importing the compiler complains that the constant is not declared. My code:

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
}

What am I doing wrong? I'm using g++ 11.1.0 on linux: g++-11 -std=c++20 -fmodules-ts test.cpp main.cpp -o main

The error message is: error: ‘my_constant’ was not declared in this scope

2 Answers

const-qualified variables have internal linkage by default, so it might be necessary to write it as

export extern const int my_constant = 42;

According to https://en.cppreference.com/w/cpp/language/storage_duration the export definition should make the variable have external linkage, so you might have hit one of the corners where C++20 is not yet fully implemented.

Simply use inline

export inline constexpr int my_constant = 42;
Related