Why does global variables in a header file cause link error?

前端 未结 5 1543
旧巷少年郎
旧巷少年郎 2020-12-11 22:03

I always get the following error, even if I have put include guard in header file.

duplicate symbol _Bittorrent in:
    /Users/tracking/Library/Developer/Xco         


        
相关标签:
5条回答
  • 2020-12-11 22:43

    Lines like

    const char    *Bittorrent     =   "BitTorrent protocol";
    const char    eight_byte[8]   =   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    

    define theses global variables no matter if that codes is in header file or ine a .c directly (#include is just textual insertion of the header's contents). Instead you should have the definitions in exaclty one source file and change the header to provide an extern declaration instead:

    extern const char *Bittorrent;
    extern const char *eight_byte;
    

    Then all your sources using thes variables can be compiled but the linker will the variables once only.

    0 讨论(0)
  • 2020-12-11 22:53

    Header:

    extern const char    *Bittorrent;
    

    Main (before the main function / as gloabal variable):

    const char    *Bittorrent     =   "BitTorrent protocol";
    

    This way your header tells every file that there is variable named "Bittorrent", but only your main.c file has the part in it where it is really created.

    0 讨论(0)
  • 2020-12-11 22:53

    By initializing the variable, you are defining it in every place that the file is included. Assuming that these modules are linked together, you now have multiple definitions, which is an error.

    You can declare the variable in your header with an extern tag and then initialize it in one of your .c modules.

    In your .h file:

    extern int i;
    

    In one of your .c files:

    int i = 1;
    

    However,

    0 讨论(0)
  • 2020-12-11 23:01

    Because you define the variables in the header file. Then all source files that includes the header file will have those variables defined.

    You can declare the variables, using the extern keyword:

    extern const char    *Bittorrent;
    extern const char    eight_byte[8];
    

    And then in one source file define the variables.

    Or you could define the variables as static, which limits their scope to the translation unit (i.e. source file):

    static const char    *Bittorrent     =   "BitTorrent protocol";
    static const char    eight_byte[8]   =   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    

    This is different from C++, where const also implies static.

    0 讨论(0)
  • 2020-12-11 23:03

    Also note that you have a typo.

    Send_fisrt_Handshake instead of Send_first_Handshake.

    I can imagine that you simply mistyped it into your question. But you never know; typos can be hard to find and fix in large code. :)

    0 讨论(0)
提交回复
热议问题