I am using gcc for compiling a number of .c files. Lets say following is the case:
C files are:
main.c
tree.c
header file is:
tree.h
I have declared some golbal variables in tree.h. Lets say following is the global varible with value assigned:
int fanout = 5;
Earlier I had kept main() function in tree.c file. And there was no problem in linking. But now i want to keep the main function separate . I just moved the main function in the newly created .c file. Now the problem is, it
shows the linkage error:
main.o error: fanout declared first time
tree.o error: multiple declaration of fanout.
Please let me know how can i get rid of this problem.
Thanks in advance,.
When you include the header file which declares and defines
int fanoutin multiple source files, you break the One Definition Rule.As per ODR, there can be only one definition of an variable in one Translation unit(Header files+source file).
To avoid it,
You need to use
externkeyword. Three simple steps:externvariableIn
tree.h:Define the variable in one of the c files(
tree.c).Then you include
tree.hin whichever source file you want to accessfanout.In
main.c: