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

前端 未结 5 1555
旧巷少年郎
旧巷少年郎 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.

提交回复
热议问题