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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With