Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a proper way to export a global constant from a module?

Declaring global constants might be convenient, but is not easy in C++. E.g. see this recent article at Fluent C++. It mostly explains how to do it, but does not mention C++20 modules.

In a regular header file on a namespace level I would declare a constant like this:

// Constants.h
inline constexpr int Count = 42;
inline const std::vector<int> Numbers = { 1, 2, 3 };  // cannot use constexpr

Here I need inline, since the symbols might be included in several translation units. IIUC, a module definition unit exporting a symbol is a separate translation unit. So I would declare it simply as following:

// Constants.ixx
export module constants;

export constexpr int Count = 42;
export const std::vector<int> Numbers = { 1, 2, 3 };  // cannot use constexpr

Is this the proper thing to do, or am I missing something?

like image 948
Mikhail Avatar asked Oct 28 '22 07:10

Mikhail


1 Answers

You did it right. Note also the important feature that, like inline in C++17, dependencies expressed via import constrain initialization order (with or without inline) in C++20.

like image 101
Davis Herring Avatar answered Oct 31 '22 09:10

Davis Herring