Wednesday, March 17, 2010

extern variable has program scope in c

extern variable has program scope in c

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
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
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.
An extern variables or functions have external linkage. An external linkage variables or functions are visible to all files.

No comments:

Post a Comment