简体   繁体   中英

Is there still a use for extern const now that we have inline variables?

I'm used to writing this sort of code:

//myInclude.h
extern const Type var;
//mySource.cpp
#include "myInclude.h"
const Type var = ...;

...but now that I can write

//myInclude.h
inline const Type var = ... ;

Is there still a use for extern const , or extern generally? Have inline variables rendered that obsolete?

inline does not have rendered extern const obsolete because they are not "orthogonal".

extern and inline when applied to a declaration of a non template const variable (as var ), declares that var does not have internal linkage. I suppose this is why one may think that inline make extern not usefull.

But extern and inline also have diverging semantics:

  • when extern appears in a declaration it implies the declaration is not a definition. It does not implies necessarily that the variable is not inline or that it is defined in an other translation unit.

  • inline means the declaration is a definition and that this same definition may appear in other translation units.

So an extern const variable declaration may still be usefull when the definition can appear in a specific translation unit. That can be used to increase compilation speed in large projects.

An other use of extern is for forward declaration of const variables. Even forward declaration of constexpr ones:

 extern const int var;
 // some code that odr-use var
 inline constexpr int var = 10;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM