praxmon
praxmon

Reputation: 5121

How does extern work?

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;

Upvotes: 4

Views: 4913

Answers (5)

Gerald
Gerald

Reputation: 23479

extern in this case indicates that the symbol a is defined in a different location, such as a different module. So the linker looks for a symbol with the same name in all of the modules that are linked, and if one exists then it sets the address to your local variable a with the address to the externally defined variable. Since you have another a defined outside of your main() function, the a inside your main() function is (basically) the same variable as the one outside.

Since the global a is initialized before the main function executes, the value is 20 by the time you access it.

Upvotes: 4

verbose
verbose

Reputation: 7917

extern as a storage class specifier tells the compiler that the object being declared is not a new object, but has storage elsewhere, i.e., is defined elsewhere. You can try this experiment with your code to see how it works. Leave out the keyword extern in your declaration of int a in main(). Then your printf() will print some garbage value, as it would be a new definition of an int with the same identifier, which would hide the global a declared elsewhere.

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254431

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.

Upvotes: 12

cpp
cpp

Reputation: 3801

You use extern to tell the compiler that the variable is defined elsewhere. Without extern in your program compiler would define another variable a (in addition to this in the global scope) in your main() function that would be printed uninitialized.

Upvotes: 2

galop1n
galop1n

Reputation: 8824

extern means i declare a variable, just like you implement a function in a source file and declare the prototype in a header to allow other source file to use it.

If you put a global variable in a source file, and use a header to declare it with the extern keyword, each source file including the header will see the variable.

The linker will do the job to tie everything just as it does with functions

Upvotes: 3

Related Questions