自己调用自己定义的函数,编译时出现"multiple definition of"错误!
我写一个程序,其中一些函数调用了自己定义的另外的函数,结果编译时出现”multiple definition of“错误,为了简化起见,我写了这个测试例子:main函数调用testA()和testB(),testA()和testB()里又都调用了另一个文件里的testC(),代码如下:
main.cpp
#include <iostream>#include <string>#include "testA.h"#include "testB.h"using namespace std;int main(){ testA(); testB(); return 0;}
//testA.h#ifndef TESTA_H#define TESTA_Hvoid testA(void);#endif//testA.cpp#include <iostream>#include "testA.h"#include "testC.h"using namespace std;void testA(void){ cout<<"A"<<endl; testC();}
//testB.h#ifndef TESTB_H#define TESTB_Hvoid testB(void);#endif//testB.cpp#include <iostream>#include "testB.h"#include "testC.h"using namespace std;void testB(void){ cout<<"B"<<endl; testC();}
//testC.h#ifndef TESTC_H#define TESTC_Hvoid testC(void);#endif//testC.cpp#include <iostream>using namespace std;void testC(void){ cout<<"C"<<endl;}
main:main.cpp testA.o testB.o testC.o g++ main.cpp testA.o testB.o testC.o -o main rm *.otestA.o:testA.cpp g++ testA.cpp -ctestB.o:testB.cpp g++ testB.cpp -ctestC.o:testC.cpp g++ testC.cpp -c
g++ testC.cpp -cg++ main.cpp testA.o testB.o testC.o -o maintestB.o: In function `testC()':testB.cpp:(.text+0x0): multiple definition of `testC()'testA.o:testA.cpp:(.text+0x0): first defined heretestC.o: In function `testC()':testC.cpp:(.text+0x0): multiple definition of `testC()'testA.o:testA.cpp:(.text+0x0): first defined herecollect2: ld returned 1 exit statusmake: *** [main] 错误 1
static void testC(void){ cout<<"C"<<endl;}
[解决办法]
你把testC.cpp删了,把函数定义放在testC.h中,加上static
然后删除.o,重新编译
[解决办法]