1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Topological Sort
  • 2,733
  • 2
  • 27
  • 54
  • 3
    Does this answer your question? [The new feature of C++17 'inline variable' vs extern keyword inherited from C](https://stackoverflow.com/questions/50623516/the-new-feature-of-c17-inline-variable-vs-extern-keyword-inherited-from-c) – Andreas is moving to Codidact Jun 07 '20 at 00:56
  • The claimed duplicate asks what the differences are (and has an answer strictly limited to that scope), while this one asks for circumstances under which each might be used. – Davis Herring Jun 07 '20 at 03:15

1 Answers1

0

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;
Oliv
  • 17,610
  • 1
  • 29
  • 72
  • What would be the practical use of having a forward declaration of a const or constexpr variable, now that we have inline? – Topological Sort Jun 07 '20 at 10:42
  • @TopologicalSort: You may want to restrict the use of a variable *as a constant expression* to one translation unit, better control the timing of its initialization, or avoid needing extensive machinery required for that initialization in every translation unit that uses the variable. – Davis Herring Jun 07 '20 at 15:55
  • @TopologicalSort Also, but even if this is not exactly the subject, forward declaration of constexpr variable is necessary for static member that have the type of their enclosing class. But there is no need for extern in this case [exemple inside the standard](http://eel.is/c++draft/cmp.partialord#1). – Oliv Jun 07 '20 at 17:36