Variables with both 'extern' and 'inline' specifiers

Viewed 383

I couldn't find any information on this topic neither from stackoverflow or elsewhere. I know that extern can be used with namespace scope variables in header files to disambiguate a definition int foo; from a bare declaration extern int foo;. That is done to avoid breaking the one-definition-rule, in case multiple files #include this same header file.

In C++17, one can use constexpr inline foo; for globals, which should be better than the old way. One could also use extern inline const/constexpr foo;, both compile without errors, but I have no idea if the extern makes any difference semantically.

So when should one use extern inline with variables, if ever? What is the best practice in C++17?

3 Answers

Based on the wording here:

Inline const variables at namespace scope have external linkage by default (unlike the non-inline non-volatile const-qualified variables)

It seems that there is never any need to add extern to an inline const(expr) variable.

Sometimes a coder prefers to put a declaration first and a definition later. extern is used for this purpose. It can be applied to a declaration of an inline variable as well. But you will not see this in small projects.

extern only means that a declaration is not a definition:

extern int i; //declaration of i
int j;        //declare and define j to be equal to zero 

inline means that the variable is inline: it can be defined in a different translation unit (TU), as long as the definition is the same, and it must be defined in every TU where it is ODR-used.

inline int k;  //declare and define k to be 0, can appear in multiple TUs
extern inline int h; //h is an inline variable but not defined
                     //it can be used to forward the definition 
int f() { return h;}
int h = 10;

There's no sense by using extern with inline. I think it's strange. You'd be giving a definition for a variable that is marked as being defined elsewhere.

You're putting the variable in the translation unit with inline, then asking for the compiler to look for it in another translation unit with extern.

Related