C++ – Should Static Global Variables Be Declared as Inline?

c++c++17globalinlinestatic

Consider, global variable (not static class member!) is declared in the header file:

inline static int i{};

It is valid construction for several compilers that I tested, and experiments demonstrate that several distinct objects will be created in different translation units, although it is also declared as inline (it means that only one instance of that variable must exist in the program). So, has static keyword more priority than inline in that case?

Best Answer

So, has static keyword more priority than inline in that case?

Pretty much. static has an effect that interferes with inline. The C++ standard states that

... An inline function or variable with external linkage shall have the same address in all translation units.

And the static qualifier imposes internal linkage, so the single address guarantee does not have to hold. Now, a name with internal linkage in different translation units is meant to denote different object in each TU, so getting multiple distinct i's is intended.

All in all, the static negates the inline. And there is no point to having a static inline variable over a plain static one.

Related Question