码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-01-06 20:06:52      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

最近编译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

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

标签:

原文地址:http://blog.csdn.net/dongfengkuayue/article/details/42463243

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!