问题
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,.
回答1:
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;
}
来源:https://stackoverflow.com/questions/8203031/linkage-errormultiple-definitions-of-global-variables