Question

I have studied in c that variables that use keyword extern are externally referenced
for example:
Prog1.c
main(){
extern int a ;
a=2;
}

Prog2.c
int a=3;
these two programs are successfully compiled together. does that means that variable a in Prog2.c is having external linkage (external reference) as well ??

but it is written in dennis ritchie pg-195 section a4.1 that the objects declared outside all blocks, at the same level as function definitions, are always static and i think static means internal linkage so what is exactly happening in the above program?

Was it helpful?

Solution

By default, an object or variable that is defined outside all blocks 
has static duration and external linkage. 

Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends. External linkage means that the name of the variable is visible from outside the file in which the variable is declared. Conversely, internal linkage means that the name is not visible outside the file in which the variable is declared.

OTHER TIPS

If you are using extern keyword then you can use the variable without declaring it in the same file. You need to declare the variable in one file and use it in all other files(modules) by using the extern keyword.

By default the global variables have external linkage unless changed by adding static keyword. This will help clarify things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top