最近编译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
时间: 2024-10-24 20:26:00