Denis
Denis

Reputation: 3082

Is there any sense to declare static global variable as inline?

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?

Upvotes: 14

Views: 1715

Answers (1)

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.

Upvotes: 13

Related Questions