首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

自己调用自己定义的函数,编译时出现"multiple definition of"异常

2012-05-04 
自己调用自己定义的函数,编译时出现multiple definition of错误!我写一个程序,其中一些函数调用了自己定

自己调用自己定义的函数,编译时出现"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_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.cpp及testB.h
C/C++ code
//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.cpp及testC.h
C/C++ code
//testC.h#ifndef TESTC_H#define TESTC_Hvoid 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 *.otestA.o:testA.cpp    g++ testA.cpp -ctestB.o:testB.cpp    g++ testB.cpp -ctestC.o:testC.cpp    g++ testC.cpp -c

编译后出现的错误如下:
C/C++ code
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

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,重新编译
[解决办法]
探讨

引用:

你把testC.cpp删了,把函数定义放在testC.h中,加上static
然后删除.o,重新编译

谢谢,找您说的,能行!但是还有个问题,能不能保持函数声明跟函数定义分离的?不是提倡这样吗?github上的代码我也更新了。

热点排行