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


i following error, if have put include guard in header file.

duplicate symbol _bittorrent in:     /users/tracking/library/developer/xcode/deriveddata/sht-giuwkwyqonghabcqbvbwpucmavvg/build/intermediates/sht.build/debug/sht.build/objects-normal/x86_64/main.o     /users/tracking/library/developer/xcode/deriveddata/sht-giuwkwyqonghabcqbvbwpucmavvg/build/intermediates/sht.build/debug/sht.build/objects-normal/x86_64/handshake.o duplicate symbol _eight_byte in:     /users/tracking/library/developer/xcode/deriveddata/sht-giuwkwyqonghabcqbvbwpucmavvg/build/intermediates/sht.build/debug/sht.build/objects-normal/x86_64/main.o     /users/tracking/library/developer/xcode/deriveddata/sht-giuwkwyqonghabcqbvbwpucmavvg/build/intermediates/sht.build/debug/sht.build/objects-normal/x86_64/handshake.o ld: 2 duplicate symbols architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation) 

here .h header file, .c file, , main.c

main.c

#include "handshake.h" int main(int argc, char** argv) {     // code.     return 0; } 

handshake.h

#ifndef sht_handshake_h #define sht_handshake_h  const char    *bittorrent     =   "bittorrent protocol"; const char    eight_byte[8]   =   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };  #endif 

handshake.c

#include "handshake.h"   int send_fisrt_handshake(download_connection *ppeer, handshake *necessary_info) {     //some statements     return 1; }  void set_handshake_information(torrentfile* parg, handshake *pyours) {      //some statements  } 

but, if deleted global variables header file, these codes compile successfully.
don't understand why. explain why? thank in advance.

lines

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 codes in header file or ine .c directly (#include textual insertion of header's contents). instead should have definitions in exaclty 1 source file , change header provide extern declaration instead:

extern const char *bittorrent; extern const char *eight_byte; 

then sources using thes variables can compiled linker variables once only.


Comments