Experimenting with global variables and functions in C -
i'm trying understand how global variables , functions work in c. program compiles , works fine gcc, not compile g++. have following files:
globals.h:
int i; void fun(); globals.c:
#include "stdlib.h" #include "stdio.h" void fun() { printf("global function\n"); } main.c:
#include "stdlib.h" #include "stdio.h" #include "globals.h" void myfun(); int main() { i=1; myfun(); return 0; } and finally, myfun.c:
#include "stdlib.h" #include "stdio.h" #include "globals.h" void myfun() { fun(); } i following error when compiling g++:
/tmp/ccozxbg9.o:(.bss+0x0): multiple definition of `i' /tmp/ccz8cpta.o:(.bss+0x0): first defined here collect2: ld returned 1 exit status any ideas why? prefer compile g++.
every file include globals.h define "int i".
instead, put "extern int i;" header file , put actual definition of "int = 1;" in globals.c.
putting header guards around globals.h sensible too.
edit: in answer question because #include works kind of cut , paste. pastes contents of included file c file calling include from. include "globals.h" main.c , myfun.c define int = 1 in both files. value, being global, gets put table of linkable values. if have same variable name twice linker won't able tell 1 needs , error seeing. instead adding extern on front in header file telling each file "int i" defined somewhere else. obviously, need define somewhere else (and in 1 place) defining in globals.c makes perfect sense.
hope helps :)
Comments
Post a Comment