Compiling the file main.c with:
gcc main1.c -o final
gives me:
/tmp/cc1cwhAP.o: In function `main':
main1.c:(.text+0xb): undefined reference to `hi'
main1.c:(.text+0x15): undefined reference to `hi'
collect2: ld returned 1 exit status
main1.c:
#include <stdio.h>
#include "incl.h"
int main(void)
{
hi = 1;
printf("hi = %d",hi);
return(0);
}
incl.h:
extern int hi;
What am I doing wrong? (Please be verbose with your answers)
Removing the extern keyword solves the issue, but I want to be able to use the hi variable in other source files.
Let’s forget about header files for a bit (after all their contents are inserted inside source files during compilation and they only exist during pre-processing). They’re only an easy way to use the same code in several source files (think copy/paste). So, in the interest of efficiency, that duplicated code should do nothing; or we risk doing something more than once.
Which of the above does less? That’s the one to put in a header file. But as we’ve told the compiler
xexists, we need to actually define it somewhere. The best place to define it is in a source file.As header files don’t do anything, they’re pretty much safe to insert into lots of source files.
Now, back to header files. They’re usually linked to a specific source file (through their names: foobar.h is linked to foobar.c). This is a good method to identify where declarations in the header file are defined.
After seeing this header file, I’d expect
foobar.cto contain the definition ofxandmyfoo.Why globals are bad?
quote from http://c2.com/cgi/wiki?GlobalVariablesAreBad