Hey I have question about extern I'm really confused. I think I have the general idea of how it works but I don't fully understand it. In all the examples I have looked at they have extern infront of the function prototype in the header file, but if I omit it in my header file, the program still works. The same thing happens if I have 2 .c files, if I declare a global variable in my main file, then have another file that uses that same variable shouldn't I have to use the extern keyword infront of my global variable in the other file? Cause when I omit it my compiler also does not complain. Im using gcc to compile.
Also if I have like say two .c files, the program still works if I remove the extern keyword infront of the variable x. Copied this from another post.Code:/*********** main.c ************/ #include <stdio.h> #include "addition.h" int main(void) { int number1, number2, result; printf("Enter number: "); scanf("%d", &number1); printf("\nEnter number: "); scanf("%d", &number2); result = add(number1, number2); printf("%d", result); return (0); } /******** addition.h ***********/ /*** If i get rid of extern it still works, why? */ /*extern*/ int add(int num1, int num2); /********** addition.c ***********/ int add(int num1, int num2) { return (num1 + num2); }
Any help would be great, confused as to why when I remove the extern keyword the program still works and I get no errorsCode:/* display.c */ #include <stdio.h> /** If I remove extern and just say int x; it still /* works, why? */ extern int x; void display( void ) { printf( "%d\n", x ); } /* main.c */ int x; int main( void ) { x = 5; display(); return 0; }![]()



LinkBack URL
About LinkBacks



