Search code examples
c++linkage

Why to add "extern" keyword if the global variable is external by default?


main.cpp

#include <iostream>

extern int g_x; // this extern is a forward declaration of a variable named g_x that is defined somewhere else

int main()
{
    std::cout << g_x; // prints 2

    return 0;
}

add.cpp

int g_x { 2 };

If I delete extern in main.cpp, then the code does not work. One the other hand, I don't need extern in add.cpp. Global variables are external by default, but still. Is it because external linkage is a "one-sided relation" between two entities that are linked in different files?


Solution

  • extern is different from external linkage. extern just means that you do a declaration, and that the variable is defined somewhere else.

    If you remove extern, int g_x will be defined in main.cpp violating ODR (since you have it defined twice).