linkage error:multiple definitions of global variables

为君一笑 提交于 2021-02-11 14:24:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!