链接错误:全局变量的多个定义 [英] linkage error:multiple definitions of global variables

查看:77
本文介绍了链接错误:全局变量的多个定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gcc编译许多.c文件.可以说是这种情况:

I am using gcc for compiling a number of .c files. Lets say following is the case:

C 文件是:

main.c 
tree.c

头文件是:

 tree.h

我在 tree.h 中声明了一些golbal变量.假设以下是分配了值的全局变量:

I have declared some golbal variables in tree.h. Lets say following is the global varible with value assigned:

 int fanout = 5;

我之前将 main()函数保存在 tree.c 文件中.链接没有问题.但是现在我想将主要功能分开.我只是将主要功能移到了新创建的 .c 文件中.现在的问题是显示链接错误:

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.

先谢谢了.

推荐答案

当您在多个源文件中包含用于声明和定义 int扇出的头文件时,就会违反一个定义规则.
根据ODR,在一个转换单元(头文件+源文件)中只能有一个变量的定义.
为了避免这种情况,
您需要使用 extern 关键字.三个简单的步骤:

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 变量

tree.h 中:

extern int fanout;   

  • 定义变量
  • 在c个文件之一( tree.c )中定义变量.

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

    #include "tree.h"   
    extern int fanout = 5;
    

    • 使用变量
    • 然后,在要访问 fanout 的任何源文件中都包含 tree.h .

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

      main.c 中:

      #include "tree.h"
      int main()
      {
          fanout = 10;
          return 0;
      }
      

      这篇关于链接错误:全局变量的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆