Code:#include<stdio.h> #include<conio.h> void fun(); void main() { int x=100; clrscr(); printf("%d",x); fun(); getch(); } void fun(){ extern int x; printf("%d",x); }
Code:#include<stdio.h> #include<conio.h> void fun(); void main() { int x=100; clrscr(); printf("%d",x); fun(); getch(); } void fun(){ extern int x; printf("%d",x); }
Change the name of your external x and it will be clearer what the problem is:
What happens when you try to compile with this definition? Notice that the x in your main function is not related to x_extern.Code:void fun() { extern int x_extern; printf("%d", x_extern); }
Yes, the error occurs because you haven't provided a definition for x_extern. Renaming x to x_extern was just to make it clear that it's not the same x. Extern means to the compiler that you (usually) intend to link the definition of that variable in from an external file. For example, here is a suitable file, that, if compiled, will satisfy the linking requirement:
Code:int x_extern = 12345;
c99tut's point is that, if a variable is local to one function, another function can't declare it as extern to gain access to it. In your code these is no relationship, whatsoever, between the x in main() and the x in fun().
The reason for the linker error is that extern tells the compiler that the variable is defined elsewhere. There is no "elsewhere" in your program that defines your extern variable.
If you want to pass a variable between two functions, either make it global (outside the scope of a function) or - preferable - define fun() so it accepts an argument of type int.
Also, main() returns int, not void. <conio.h> and getch() are also not standard C.