链接错误:全局变量的多个定义
我正在使用 gcc 编译许多 .c 文件。让我们说以下情况:
C 文件是:
main.c
tree.c
头文件是:
tree.h
我已经在 tree.h
中声明了一些全局变量。可以说以下是已赋值的全局变量:
int fanout = 5;
早些时候,我将 main()
函数保留在 tree.c
文件中。而且链接起来也没有问题。但现在我想将主要功能分开。我刚刚将 main 函数移至新创建的 .c
文件中。现在的问题是,它 显示链接错误:
main.o error: fanout declared first time
tree.o error: multiple declaration of fanout.
请让我知道如何解决这个问题。
提前致谢,。
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,.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在多个源文件中包含声明和定义
int fanout
的头文件时,您就违反了单一定义规则。根据ODR,一个翻译单元(头文件+源文件)中只能有一个变量的定义。
为了避免这种情况,
您需要使用
extern
关键字。三个简单步骤:extern
变量在
tree.h
中:在 c 文件之一中定义变量(
tree.c
)。然后将
tree.h
包含在您想要访问fanout
的源文件中。在 main.c 中:
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:extern
variableIn
tree.h
:Define the variable in one of the c files(
tree.c
).Then you include
tree.h
in whichever source file you want to accessfanout
.In
main.c
: