I would just like to know what the "extern" statement is used for in c++, and when/why it is used?.
Thanks.
4 Answers
This is quite a good explaination: http://msdn.microsoft.com/en-us/library/0603949d.aspx
Basically it specifies the storage - a declaration with the 'extern' keyword specifies that the variable has external linkage - it does not require storage space in the current context and will be defined in the some or other unit without the extern
modifier, which if not done, will turn into a linker error about a missing reference, since it has been told there is a variable that is not there. An example could be a shared item between a library and multiple clients, that is declared extern
in a header so that the clients know about it, but the storage is actually in the library so that when accessing it, they use the right value, not a value with a storage space allocated inside the unit that included the file with the declaration. E.g.
Some header:
...
extern int dummy; // tells the unit that there is an integer dummy with storage speace somewhere else
...
dummy = 5; // actually changes the value defined in some other cpp file in the library
Some cpp file in the library:
...
int i; // references to i if not shadowed by other declarations reference this value

- 11,636
- 6
- 33
- 71
It means that the variable is external to this compilation unit, i.e. it has been declared in a different compilation unit.

- 27,315
- 3
- 37
- 54
It will search the already initialization of that variable.
If declared an extern variables or function globally then its visibility will whole the program which may contain one file or many files. For example consider a c program which has written in two files named as one.c and two.c:
//one.c
#include<conio.h>
int i=25; //By default extern variable
int j=5; //By default extern variable
/**
Above two line is initialization of variable i and j.
*/
void main(){
clrscr();
sum();
getch();
}
//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern)
*/
void sum(){
int s;
s=i+j;
printf("%d",s);
}
Compile and execute above two file one.c and two.c at the same time

- 1,043
- 1
- 13
- 38
Declaring something as extern
tells the compiler it is declared elsewhere in the solution, so it will not complain that it is undefined OR defined multiple times.

- 869
- 5
- 23