Can someone demonstrate how an external variable is accessed from one file to another? Also how do we use it when we have already defined the external variable in the source file?
How is an external variable is accessed from one file to another?
Collapse
X
-
-
you use the extern keyword to declate an external identifier, see this discussion on storage specifiers
e.g. file data.c
Code:int data;
Code:extern int data; // declare external identifier int main() { data = 10; // use external identifier printf("%d\n", data); }
gcc test.c data.c -
okay i got that how to declare....but if i am defining a variable in one file say test.c and i want it to be used in other file..then in test.c,do i have to prefix extern before variable definition,,, like extern int a=20; ...and if not then howcome in any file making an extern declaration of varibale a will help me access the variable -a- of file test.c.........Comment
-
you define the variable (allocate memory for it) in one file (and you can initialise it here)
Code:int data=100; // define the variable
Code:extern int data; // declare the variable
don't initialise the varaiable when you declare it, e.g.
Code:extern int data=10; // declare the variable
Code:ADNS6090.c:60: warning: 'data' initialized and declared 'extern'
Comment
-
-
-
supppose i have defined a variable in some other file say external.c but i have not included that file in my present file test.c...and if i make an extern declaration of the same variable..then will i be able to access it...Comment
-
"Including" is not important. Your files have to end up looking something like what horace1 showed you. It doesn't matter if you achieve that content with include files or by putting the statements directly into the c source file. Each of your c source files is compiled separately and individually into an object file. Then all of the object files are linked together. It is the link step that resolves references to global variables.Comment
Comment