How does a global variable declared as extern differ from a global variable declared

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • radha gogia
    New Member
    • Feb 2015
    • 56

    How does a global variable declared as extern differ from a global variable declared

    Say If I write

    extern int y;

    and then I write

    int y ;

    so I cannot access the y variable anywhere now since it is uninitialized while the second one is initialized to zero but we say that default value of extern varibale is zero so then why is this extern int y declaration used globally ?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Here you need to understand about linkage. There is internal linkage and there is external linkage.

    External linkage allows you to use the variable in more than one file. Internal linkage allows you to use the variable in only the file where it is created.

    By default the linkage of global variables is external.

    So this code:

    Code:
    extern int i;
    tells the compiler not to create a variable i because there is one already in another file that as external linkage.

    Code:
    extern int i = 10;
    This tells the compiler to create a variable i with an initial value of 10. The extern here for external linkage is not necessary since linkage of global variables is external by default.

    Code:
    static int i;
    This code says t create a variable i with an initial value of zero and with internal linkage. This variable is inaccessible outside the file where the variable is created. An extern i in another file cannot access this variable.

    As to why global variables in the first place read this: http://bytes.com/topic/c/insights/73...obal-variables

    Comment

    Working...