C/c
Expert: Zlatko - 12/9/2011
Question3)sir my doubt is about extern storage class.”when we have a global variable defined in one c file if we want to use it in another c file then we have to declare it as extern in another file.then I have done the following .”this is my knowledge about extern. you gave me these lines in your last response.i found these lines in my book too.still I have doubt in extern.
First I have written the following code and saved it as 1.c
#include<stdio.h>
#include<conio.h>
Int i=35;
Int fun1();
Void main()
{
Clrscr();
Fun1();
getch();
}
After this I have written the following code and saved it as 2.c
#include”1.c”
Int fun1()
{
Printf(“%d”,i);
return 0;
}
If run the programme 2.c I got 35 as out put.here in 2.c I am using the global variable of 1.c i.e I, with out extern.i was successful in executing this programme.
How is it possible?your explanation is correct.but still I am not able to under stand the extern.
I want your help in understanding extern with small programme..
AnswerHello Phaneendra
You may have gotten the 35 output because you included 1.c into 2.c. That is not how to do it. You should not include one c file into another. The output looks right to you but the reason you are getting the output is not because of extern.
Here is how to do it.
make a header file.
/* declarations.h */
extern int i;
void fun();
make a c file
/* file1.c */
#include "declarations.h"
int i = 35;
void main()
{
fun();
}
make another c file
/* file2.c */
#include "declarations.h"
void fun()
{
printf("i is %d\n", i);
}
Notice that each c file includes the same declarations.h file. This lets the compiler check the correctness of the header file against all the definitions and all the uses of the functions and variables. For example, if the header file says that i is int, and file2.c uses i as int, but file1.c says i is a float, the compiler would catch that error. If the header file says that fun takes no arguments, but fun in file2 is written to take arguments, the compiler would catch that error. The header file is used to check that everything matches up.
Now you must feed each C file into the compiler, and the compiler creates an object file out of each C file. Next, you must feed the two object files into a linker and that will make the executable. Sometimes, the compiler calls the linker automatically, and you may not even see the object files being made. The compiler and linker will make sure that the i in file1 and the i in file2 are the same i. You don't need to worry about how that is possible, you just need to know that it is the rule.
Notice also that you do not send the header file to the compiler but the compiler will find and read the header file for each C file being compiled.
How to call the compiler and linker depends on which compiler you are using, so I cannot give you details about that because I don't know what you are using.
Best regards
Zlatko