Search code examples
c++referenceextern

Why make a extern variable a reference?


I stumbled upon some code like this:

extern Space::MyClass &Global;

I know about extern, but my question is, why would someone put the ampersand there? What's the difference between that and the following?

extern Space::MyClass Global;

Solution

  • The extern must match the actual definition of the variable.

    Presumably one of the other units contains:

     Space::MyClass &Global = whatever....;
    

    That means that you have to pick it up with extern Space::MyClass &Global;. Mismatching the types in an extern declaration causes undefined behaviour (no diagnostic required).