Linux C++编译报错:"multiple definition of" / "does not name a type"

19 篇文章 1 订阅

最近编译larbin_daemon爬虫服务器端管理程序时,总是会报如下的错误:

g++    -c -o editConf.o editConf.cpp
editConf.cpp:49:8: error: redefinition of ‘std::string projectG’
editConf.h:34:8: error: ‘std::string projectG’ previously declared here
editConf.cpp:50:8: error: redefinition of ‘std::string ipG’
editConf.h:35:8: error: ‘std::string ipG’ previously declared here
editConf.cpp:51:8: error: redefinition of ‘std::string httpPortG’
editConf.h:36:8: error: ‘std::string httpPortG’ previously declared here
editConf.cpp:52:8: error: redefinition of ‘std::string pagesConnexionsG’
editConf.h:37:8: error: ‘std::string pagesConnexionsG’ previously declared here
editConf.cpp:53:8: error: redefinition of ‘std::string dnsConnexionsG’
editConf.h:38:8: error: ‘std::string dnsConnexionsG’ previously declared here
editConf.cpp:54:8: error: redefinition of ‘std::string depthInSiteG’
editConf.h:39:8: error: ‘std::string depthInSiteG’ previously declared here
editConf.cpp:55:8: error: redefinition of ‘std::string waitDurationG’
editConf.h:40:8: error: ‘std::string waitDurationG’ previously declared here
editConf.cpp:56:8: error: redefinition of ‘std::string timeoutPageG’
editConf.h:41:8: error: ‘std::string timeoutPageG’ previously declared here
editConf.cpp:57:8: error: redefinition of ‘std::string timeoutIncrG’
editConf.h:42:8: error: ‘std::string timeoutIncrG’ previously declared here
make: *** [editConf.o] Error 1

十分困惑,明明只定义了一次嘛!

其实,

editConf.h中,有如下代码片段:

string projectG;//G代表global,类中也有对应的私有变量
string ipG;
string httpPortG;
string pagesConnexionsG;
string dnsConnexionsG;
string depthInSiteG;
string waitDurationG;
string timeoutPageG;
string timeoutIncrG;

然后在editConf.cpp中是直接用了(赋值什么的)如:

httpPortG = r[6];

在editConf.cpp和main.cpp中都包含了editConf.h头文件,这就问题所在。


当你在头文件中声明一个变量,就像我在editConf.h中写的,每个包含了该头文件的源文件,无论是直接的还是间接的,都会获得一个它自己对于该变量的拷贝,那么当你link所有的.o文件到一起时候,linker就会认为该变量在多个.o文件中被实例化了。

解决的方法是:在头文件中(如editConf.h)用extern声明变量,在对应的源文件中(如editConf.cpp)实例化变量。


参考资料:

http://stackoverflow.com/questions/18763270/c-linking-error-with-multiple-definition-on-linux

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值