Search code examples
c++c++11global-variablesexternlinkage

How C++ differentiates between a call to global variable and declaration of a global variable?


This is the most confusing part for me from section Global Variables and linkage properties.

  extern int g_var1;

Statement could be something like this when defining an external non-const global variable. I think I will write exactly the same for using that variable (through forward-declaration) in some other file. If both the statements are same, how C++ knows whether the variable was declared or was defined in a file?


Solution

  • When you say extern int g_var1; the variable is just declared, and later when you have to use it you can use it directly.

    file1.cpp:

    int g_var1;
    

    File2.cpp:

    extern int g_var1;
    

    You need not to write extern everytime. Though i would suggest if you have to use global variables place them in a separate header file.