为什么在头文件引起链接错误全局变量? [英] Why does global variables in a header file cause link error?

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

问题描述

我总是碰到下面的错误,即使我已经把包含头文件中后卫。

I always get the following error, even if I 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 for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

下面是.H头文件,.c文件,和main.c中

Here are .h header file, .c file, and main.c

的main.c

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

Handshake.h

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

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

}

但是,如果我删除了全局变量的头文件,这些codeS编译成功。结果
我不明白为什么。可能有人解释一下为什么?谢谢你在前进。

But, If I deleted global variables from header file, these codes compile successfully.
I don't understand why. Could someone explain why? Thank you in advance.

推荐答案

行像

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

论文定义全局变量,无论如果codeS是在头文件或直接INE .c的(的#include 是头部的内容,只是文本插入) 。
相反,你应该在exaclty一个源文件中的定义和改变头,可以提供一个的extern 声明来代替:

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;

然后使用THES变量的所有源可以被编译,但是链接器将变量只有一次。

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

这篇关于为什么在头文件引起链接错误全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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