Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does extern work?

Tags:

c++

c

extern

extern is a storage class in C. How exactly does it work? The output of the code given below is 20. How is this the output?

#include <stdio.h>

int main()
{
    extern int a;
    printf("%d", a);
    return 0;
}
int a=20;
like image 962
praxmon Avatar asked Nov 29 '22 08:11

praxmon


1 Answers

It means three things:

  • The variable has external linkage, and is accessible from anywhere in the program;
  • It has static storage duration, so its lifetime is that of the program (more or less); and
  • The declaration is just a declaration, not a definition. The variable must also be defined somewhere (either without the extern, or with an initialiser, or in your case, both).

Specifically, your extern int a; declares that the variable exists, but doesn't define it at that point. At this point, you can use it, and the linker will make sure your use refers to the definition. Then you have the required definition, int a=20; at the end, so all is well.

like image 65
Mike Seymour Avatar answered Dec 10 '22 10:12

Mike Seymour