Quick Q: use of constexpr in header file

Quick A: const in a header implicitely means static.

Recently on SO:

use of constexpr in header file

constexpr implies const and const on global/namespace scope implies static (internal linkage), which means that every translation unit including this header gets its own copy of PI. The memory for that static is only going to be allocated if an address or reference to it is taken, and the address is going to be different in each translation unit.

That implied static for const variables was introduced specifically to use const instead of #define in header files in C++ to define constants. Without static there would be multiple symbol definitions linker error if that header file is included in more than one translation unit which were linked together.

In C++17 you can also make it inline, so that there is only ever a single copy of PI if an address or reference to it is taken (i.e. not static). inline variables were introduced in C++17 to allow for header-only libraries with non-const variable definitions in the header files.

In other words, you should use constexpr for your constants in header files, if possible, otherwise const. And if you require the address of that constant to be the same everywhere mark it as inline.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.