0

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,.

infused
  • 24,000
  • 13
  • 68
  • 78
thetna
  • 6,903
  • 26
  • 79
  • 113

1 Answers1

3

When you include the header file which declares and defines int fanout in 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 extern keyword. Three simple steps:

  • Declare the extern variable

In tree.h:

extern int fanout;   
  • Define the variable

Define the variable in one of the c files(tree.c).

#include "tree.h"   
extern int fanout = 5;
  • Use the variable

Then you include tree.h in whichever source file you want to access fanout.

In main.c:

#include "tree.h"
int main()
{
    fanout = 10;
    return 0;
}
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • BTW, i am getting the following warning:**warning: 'fanout' initialized and declared 'extern'**.Do you have any idea why it so? – thetna Nov 20 '11 at 17:18
  • 1
    @thetna: You may want to check [this](http://stackoverflow.com/questions/8054847/declaration-versus-definition-in-c/8054893#8054893) answer of mine.You might also just do `int fanout = 5` in tree.c` excluding the preceding `extern`, that will get you rid of the warning though the warning is just Idiomatic warning, The usage in the above answer is safe and standard compliant,the linked answer explains this in detail. – Alok Save Nov 20 '11 at 17:23