- 论坛徽章:
- 0
|
各位,小弟请教一个关于头文件中定义函数,在编译时出现重复定义的问题
小弟发现在头文件中加入于预编译控制
#ifndef ***
#define ***
……
#endif
只能防止变量的重复定义错误,而不能保证函数的重复定义错误,
比较郁闷
小弟写了一段测试程序,各位大大帮忙看看
1。head.h
#ifndef __HEAD__
#define __HEAD__
int e;
int i(){
printf("%d\n",e);
return e;
}
#endif
2. head1.c
#include <stdio.h>
#include "head.h"
extern int j();
main(){
e=0;
e++;
i();
j();
}
3. head2.c
#include <stdio.h>
#include "head.h"
int j(){
printf("%d\n",e);
return e;
}
gcc head1.c head2.c 出现如下错误
/tmp/ccLzdy1P.o(.text+0x0): In function `i':
: multiple definition of `i'
/tmp/ccurivKz.o(.text+0x0): first defined here
collect2: ld returned 1 exit status
在head.h 中的int i()前加上 static 可以避免该问题,但不想这样用
还有在c++的类定义时,如果把类定义和成员函数实现都写在头文件里的话,多次引用该头文件也会出现同上面类型相同的错误 |
|