I have the following codes:
(1) extern_test.h:
extern int give_something;
(2) extern_test.c:
#include <stdio.h>
#include "extern_test.h"
int give_something = 10;
(3) extern_test2.c:
#include <stdio.h>
#include "extern_test.h"
int main()
{
printf("%i\n", give_something);
return 0;
}
Now when I compile extern_test2.c on terminal, it says "undefined reference to 'give_something'".... Please help why this doesn't work..
An "Undefined Reference" means that the code is written fine, but once all the different files are compiled and it's time to link them together, one of the files doesn't have the thing you're looking for (in this case, give_something
). This is called a linker error.
The problem is most likely that you aren't using the correct command line for the compiler - you're attempting to compile extern_test.c
and extern_test2.c
into two separate binaries. Thus, when you compile extern_test.c
it works fine, but when you attempt to compile extern_test2.c
it can't find the variable because it was declared in extern_test.c
.
Assuming you're using g++, use this command line:
g++ extern_test.c extern_test2.c
Notice how they are both compiled together. There are fancier commands that allow you to compile each one individually into an object file, then link them all together afterward with a third command, but that isn't necessary here.