Keyword extern is used for declaring extern variables in c. This modifier is used with all data types like int, float, double, array, pointer, structure, function etc.
Important points about extern keyword:
1. It is default storage class of all global variables as well all functions. For example, Analyze following two c code and its output:
(a)
#include <stdio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 0
(b)
#include <stdio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: Compilation error, undefined symbol i.
Question: In Both program variable i is extern variable. But why output is different? Read second and third points.
(c)
#include <stdio.h>
void sum(int,int) //By default it is extern.
int main(){
int a=5,b=10;
sum(a,b);
return 0;
}
void sum(int a,int b){
printf("%d”",a+b);
}
Output: 15
2. When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable. Hence in second case compiler is showing error unknown symbol i. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables. For example:
#include <stdio.h>
extern int i=10; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 10
3. If you will not use extern keyword with global variables then compiler will automatically initialize with default value to extern variable.
4. Default initial value of extern integral type variable is zero otherwise null. For example:
#include <stdio.h>
char c;
int i;
float f;
char *str;
int main(){
printf("%d %d %f %s",c,i,f,str);
return 0;
}
Output: 0 0 0.000000 (null)
5. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:
(a)
#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable
//locally.
printf("%d",i);
return 0;
}
Output: Compilation error: Cannot initialize extern variable.
(b)
#include <stdio.h>
int main(){
extern int i; //Declaration of extern variable i.
int i=10; //Try to locally initialization of
//extern variable i.
printf("%d",i);
return 0;
}
Output: Compilation error: Multiple declaration of variable i.
6. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example:
(a)
#include <stdio.h>
int main(){
extern int i; //It will search the initialization of
//variable i.
printf("%d",i);
return 0;
}
int i=20; //Initialization of variable i.
Output: 20
(b)
#include <stdio.h>
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
extern int i=20; //Initialization of extern variable i.
Output: 20
(c)
#include <stdio.h>
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
static int i=20; //Initialization of static variable i.
Output: 20
(d)
#include <stdio.h>
int main(){
extern int i; //variable i has declared but not
//initialized
printf("%d",i);
return 0;
}
Output: Compilation error: Unknown symbol i.
7. A particular extern variable can be declared many times but we can initialize at only one time. For example:
(a)
extern int i; //Declaring the variable i.
int i=25; //Initializing the variable.
extern int i; //Again declaring the variable i.
#include <stdio.h>
int main(){
extern int i; //Again declaring the variable i.
printf("%d",i);
return 0;
}
Output: 25
(b)
extern int i; //Declaring the variable
int i=25; //Initializing the variable
#include <stdio.h>
int main(){
printf("%d",i);
return 0;
}
int i=20; //Initializing the variable
Output: Compilation error: Multiple initialization variable i.
8. We cannot write any assignment statement globally. For example:
#include <stdio.h>
extern int i;
int i=10; //Initialization statement
i=25; //Assignment statement
int main(){
printf("%d",i);
return 0;
}
Output: Compilation error
Note: Assigning any value to the variable at the time of declaration is known as initialization while assigning any value to variable not at the time of declaration is known assignment.
(b)
#include <stdio.h>
extern int i;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}
int i=10; //Initialization statement
Output: 25
9. 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:
(a)
//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:
In Turbo c compiler
Step 1: Write above two codes in the file named as one.c and two.c (You can give any name as you like) and save it.
Step 2: In Turbo c++ IDE click on Project -> Open project menu as shown in following screen dump.
Step 3: After Clicking on open project you will get following screen:
In Open project File text field write any project name with .prj extension. In this example I am writing project name as CProject.PRJ. Now press OK button.
Step 4: After pressing OK button you will get following screen:
Now click on Project -> Add item menu.
Step 5: After clicking Add item you will get following screen:
In the name text field write down all c source code file one by one i.e. first write one.c and click on Add button
Then write two.c and click on Add button and so on
Step 6: At the end click on Done button. After clicking on done button you will get following screen:
At the lower part of window you can see project name, list of files you have added etc.
Step7: To compile the two files press Alt+F9 and to run the above program press Ctrl+F9
Note: To close the project click on Project -> Close project.
Output: 30
Hence we can say variable i and j which has initialized into two.c is also visible in file one.c. This example proves visibility of globally declared extern variable is program.
Note: In the above example function sum which was declared and defined in two.c has also storage class extern. So we can call from other file (one.c).If it will static then we cannot call function sum since static storage class is only visible to the file where it has declared.
10. An extern variables or functions have external linkage. An external linkage variables or functions are visible to all files.
53 comments:
why initialisation must required for variables that declare globally with extern keyword....and why initialisation not required for variables that declared globally without extern keyword..plz explain the diffrence...clearly..iam waiting for ur concerned replay..
Hi Ranjith,
When we use extern keyword with uninitialized variable compiler think variable has initialized somewhere else in the program while when we don't use extern keyword then compiler initialized it with default value.
thanks....
nice workk..
excellent site.:D
plz define breifly what was external linkage and internal linkage...?
what is declaration?
declaration is nothing but any variable can be declared to a particulat data type before using it in a program ,so that compiler can allocate space for them in memory
Very nicely explained. Nice blog.
very nice explanations and examples..thanks for such a great article.
nicely explained...thanks
Great work.Thanks to u.
nice work.thank u.
Thank you very much,,,
Now i learned all Storage classes from you explanation that's really very good explanations...
thank you...!!!! :)
great explanation thank u...
Good Explanation:)
awesum
Can we use extern variables amoung different processes & threads? give examples.
great work.... thanks a lot :)
it is the best explanation i have ever seen. :-)
thank you..
5.B) is wrong bro.!
Check the output.please
It's awesome work
if i declare and define a variable globly in one file namly "firstfile.c".and i m using this variable in another file just adding #include"firstfile.c".and its working without using extern keyword.....so i want to ask that then what is the use of extern keyword....just try any program without using extern where r u using extern,it will work...
Thank you very much for your clarification...Teaching is a great work..
It is not wrong sice the extern variable is declared localy
In c there are 3 types of linkages 1.External 2.Internal 3. no linkage
1.Global variable comes under this group. ex: Extern
2.static comes under this type
3.Local variable comes under this group.
in external the variable scope is within entire file, but in local variables the scope is within braces where no linkage is not required.
thanku for a nice n understandin explanation
hi
#include
//extern int i;
int main(){
extern int i;
i=25;
printf("value of extern variable : %d\n",i);
return 0;
}
for the above program, ouput iam getting is compilation error.
and
#include
//extern int i;
int main(){
extern int i;
i=25;
printf("value of extern variable : %d\n",i);
return 0;
}
int i;
for the aboue program iam getting output is 25.
iam confused, what is the difference between the two programs?
would please explain any one of you?
hi good question
I think that as extern keyword only declare the variable ,no memory is allocated to it.Memory is allocated when you initilise it this can be done through int i;or int i=any_value;
In first case you didn't initialise but assignment is done.
While in second by writing int i; in last you initialise it .
This is according to how compiler work whenever it sees declaration it try to find initialisation in second case it finds and initialise value by 0 then comes to i=25 hence you got the answer.
This is little basic idea .I hope it helps you.
in 3rd point it says the extern keyword looks for the intialization globally... and multiple declarations cannot be accepted bt in the 8b y local variable is given as output either it throw compilation error for multiple declarations or it should take the value of 10 , please clarify the doubt
#include
extern int i;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}
int i=10;
hi I WANT A PROGRAM ....ON STORAGE CLASSES.....QUESTION IS WRITE AC PROGRAM TO ILLUSTRATE AUTO,REGISTER,STATIC,EXTERN.
Basically, extern keyword is a default storage class. If you do not declare the keyword globally then it will take as zero or null but if you declare extern keyword globally then you need to initialize it . Now locally, if you do not declare extern keyword then the compiler will take it as a default storage class viz auto. Auto is a default storage class. So it is necessary to declare extern keyword locally. Globally extern keyword is default.
nice explanation....thank you....
sema........
Is there any difference between following declarations?
1 : extern int fun();
2 : int fun();
A. Both are identical
B. No difference, except extern int fun(); is probably in another file
C. int fun(); is overrided with extern int fun();
Thanks a lot :)
One Correction
Default storage class for global variable in static
It's very useful
great tutorials....tnku bro....is there any tutorial for "how to add functions in library" here.if yes pls show me??
I have a doubt regarding to conversion of int to
char or vice-versa.
If we want to convert int to char then we use something like this.
void main()
{
int ch=65;
printf("%c",ch);
}
In memory 'ch' occupies 2 bytes.So,when its time to convert 'ch' into
char using %c it only use the lower byte,means the right most byte &
corresponding to that byte whatever is the character it prints out.But
when its time to convert char to int we use something like this.
void main()
{
char ch='a';
printf("%c",ch);
}
In memory 'ch' occupies 1 byte.So,when its time to convert 'ch' into
int using %d,so the compiler reserved 1 extra byte to the right of
it.But we don't know what is present in this byte.But still we get the
correct answer.How?
Nice Explanation, But i'm having one doubt in
#include
int main(){
extern int i; //It will search the any initialized
//variable i which may be static or
//extern.
printf("%d",i);
return 0;
}
I'm getting this Err....
"9 12 I:\Program\c\Array\rough.c [Error] static declaration of 'i' follows non-static declaration"
in Dev-C++ Compiler
static int i=20; //Initialization of static variable i.
#include
int main()
{char far*s1,*s2;
printf("%d%d",sizeof(s1),sizeof(s2));
return 0;
}
for the above programme i got output as 4,2.can any one explain me how it possible?
In one of the above example's above you have shown that if we write an extern variable which is from the different file it should be initialized otherwise it will through an error but why dint you initialize i and j in the example ? I did the same but it was giving error
every pointer can stores only address. so, generally address requires 2 bytes of memory space. it dos enot depends upon type(int or char or float) . But you are declaring far pointer (char far*s1).It has 4 bytes memory space. please check for this
super helpful
Best tut....
For better understanding of "extern" Here i and using a var1.c file as:
var1.c:
#include"var2.c"
int main()
{
printf("%d \n"sizeof(i));
}
and file var2.c:
#include
extern int i;
int abc()
{
int j=0;
printf("hello");
}
o/p: 4
var1.c:
#include"var2.c"
int main()
{
printf("%d %d\n"sizeof(i),&i);
}
and file var2.c:
#include
extern int i;
int abc()
{
int j=0;
printf("hello");
}
o/p: Error: undefined refernce to 'i'
Because extern just declares the variable not assigning any address.
From my analysis, We need to use extern for all global variables as you consists of more files for a program as if we require variables, but initialization can be done at any point of time and memory can be also saved. As C like low level programming languages mostly concentrates on memory.
Awesome boss Explanation was faduuu
thanz for the pleasant explanation
If a variable is defined externally it is not extern it is static by default please change it. Cause only static gives the output as zero
I was wondering if you could tell me what this means as it is the name of a withdrawal from my bank account.
OUTPUTON.C 39.95_V
The examples are the real gems of this blog post.Other sites hardly showcase such nicely framed examples contrasted with different situations that a programmer might face>
THANKS A LOT!!!!!
Post a Comment