multiple definition of 函数
场景:自己调用自己定义的函数,编译时出现"multiple definition of"异常
自己调用自己定义的函数,编译时出现"multiple definition of"错误!
我写一个程序,其中一些函数调用了自己定义的另外的函数,结果编译时出现”multiple definition of“错误,为了简化起见,我写了这个测试例子:main函数调用testA()和testB(),testA()和testB()里又都调用了另一个文件里的testC(),代码如下:
main.cpp
testA.cpp及testA.h
testB.cpp及testB.h
testC.cpp及testC.h
Makefile
编译后出现的错误如下:
os:linux,编译器:gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
我搜了老半天,之前是testC()函数的声明和定义都放在testC.h里,编译出错,后来分成.h和.cpp两个文件,在.h文件里加extern,在testB.h和testA.h里加testC()的声明等等都试过,就是没法编译成功。只有来向大家求助了!多谢了!
------解决方案--------------------
在testc之前加上static应该就没有问题了
自己调用自己定义的函数,编译时出现"multiple definition of"错误!
我写一个程序,其中一些函数调用了自己定义的另外的函数,结果编译时出现”multiple definition of“错误,为了简化起见,我写了这个测试例子:main函数调用testA()和testB(),testA()和testB()里又都调用了另一个文件里的testC(),代码如下:
main.cpp
- C/C++ code
#include <iostream> #include <string> #include "testA.h" #include "testB.h" using namespace std; int main() { testA(); testB(); return 0; }
testA.cpp及testA.h
- C/C++ code
//testA.h #ifndef TESTA_H #define TESTA_H void testA(void); #endif //testA.cpp #include <iostream> #include "testA.h" #include "testC.h" using namespace std; void testA(void) { cout<<"A"<<endl; testC(); }
testB.cpp及testB.h
- C/C++ code
//testB.h #ifndef TESTB_H #define TESTB_H void testB(void); #endif //testB.cpp #include <iostream> #include "testB.h" #include "testC.h" using namespace std; void testB(void) { cout<<"B"<<endl; testC(); }
testC.cpp及testC.h
- C/C++ code
//testC.h #ifndef TESTC_H #define TESTC_H void testC(void); #endif //testC.cpp #include <iostream> using namespace std; void testC(void) { cout<<"C"<<endl; }
Makefile
- C/C++ code
main:main.cpp testA.o testB.o testC.o g++ main.cpp testA.o testB.o testC.o -o main rm *.o testA.o:testA.cpp g++ testA.cpp -c testB.o:testB.cpp g++ testB.cpp -c testC.o:testC.cpp g++ testC.cpp -c
编译后出现的错误如下:
- C/C++ code
g++ testC.cpp -c g++ main.cpp testA.o testB.o testC.o -o main testB.o: In function `testC()': testB.cpp:(.text+0x0): multiple definition of `testC()' testA.o:testA.cpp:(.text+0x0): first defined here testC.o: In function `testC()': testC.cpp:(.text+0x0): multiple definition of `testC()' testA.o:testA.cpp:(.text+0x0): first defined here collect2: ld returned 1 exit status make: *** [main] 错误 1
os:linux,编译器:gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
我搜了老半天,之前是testC()函数的声明和定义都放在testC.h里,编译出错,后来分成.h和.cpp两个文件,在.h文件里加extern,在testB.h和testA.h里加testC()的声明等等都试过,就是没法编译成功。只有来向大家求助了!多谢了!
------解决方案--------------------
在testc之前加上static应该就没有问题了
- C/C++ code
static void testC(void) { cout<<"C"<<endl; }
------解决方案--------------------
你把testC.cpp删了,把函数定义放在testC.h中,加上static
然后删除.o,重新编译
------解决方案--------------------