简体   繁体   中英

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?

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).

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