Search code examples
c++extern

Use case for initialized extern variable


I realized that I can define an extern variable, like:

source.cpp

extern int i = 42; // definition, can very well just remove the `extern`

main.cpp

#include <iostream>

extern int i; // declaration

int  main()
{
    std::cout << i << std::endl;
}

I can then compile and link the program,

g++ main.cpp source.cpp

and it runs and correctly displays 42. The warning I get is

warning: 'i' initialized and declared 'extern' (gcc)

warning: 'extern' variable has an initializer (clang)

Using int i = 42; in source.cpp has exactly the same overall effect.

My question: is there any non-trivial use case for variables defined extern (not just declared then defined in another translation unit)? Is such a definition even standard compliant?


Solution

  • The extern specifier is useful in conjunction with variables that would have internal linkage without it, such as constants at namespace scope:

    a.cpp:

    extern const int n = 10;  // external linkage
    

    b.cpp:

    int main()
    {
        extern const int n;   // finds the n defined in the other TU
        return n;
    }