0

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?

akash
  • 1,801
  • 7
  • 24
  • 42
  • In your case it is not static. you are referencing a global valiable declared in prog2.c in prog1.c. If you declare the variable in a file at same level as functions and then use it in your fucntions in the same file, it has static scope. – Jack May 24 '13 at 07:20
  • but i think in prog2 a is declared at the same level as any other function definition would be in it – akash May 24 '13 at 07:25

2 Answers2

2
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.

Dayal rai
  • 6,548
  • 22
  • 29
  • you mean static and internal linkage are two different things? – akash May 24 '13 at 07:19
  • When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. – Dayal rai May 24 '13 at 07:24
  • so is the variable a having internal linkage? – akash May 24 '13 at 07:25
  • No, variable a have external linkage because it is there with extern keyword.it is local to a function so you needed to put extern to make external linkage for it.If you define variable as globel it will have exeternal linkage by default. – Dayal rai May 24 '13 at 07:49
0

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.

Community
  • 1
  • 1
Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84