I am having a lot of issue using extern variable and header files. I have read through sections of books and searched the web for hours but I haven't been able to figure out. Any help in understanding this problem will be greatly appreciated. The following is the code and the error when I try to compile
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sample.h" int main() { int i; int gI = 0; double recv; i = 10; gI = i; recv = AnotherFunc(); return 0; } And the sample.h is the following
#ifndef SAMPLE #define SAMPLE extern int gI; extern double AnotherFunc(); #endif And the other is function is
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sample.h" double AnotherFunc() { double someVar; int test; test = gI; someVar = 10.0; return someVar; } When I compile the following way, I get the following errors which I don't understand why I am getting those errors. sample.h has the variable declaration and it should be visible in the AnotherFunc.
gcc -Wall -ansi -pedantic -c Main.c AnotherFunc.c gcc Main.o AnotherFunc.o -o test AnotherFunc.o: In function `AnotherFunc': AnotherFunc.c:(.text+0x6): undefined reference to `gI' collect2: ld returned 1 exit status I only added the int gI = 0; because I wanted to define it. If I modify the code in the following way I get error in main also. Please see below.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sample.h" int main(int argc, char *argv[]) { int i; double recv; i = 10; gI = i; recv = AnotherFunc(); return 0; } gcc -Wall -Wstrict-prototypes -ansi -pedantic -c Main.c AnotherFunc.c gcc Main.o AnotherFunc.o -o test Main.o: In function `main': Main.c:(.text+0x1b): undefined reference to `gI' AnotherFunc.o: In function `AnotherFunc': AnotherFunc.c:(.text+0x6): undefined reference to `gI' collect2: ld returned 1 exit status
gIas local tomain()- you need to declare it outside ofmain(), at global level.