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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top