您的位置:首页 > 其它

不要在头文件中定义变量

2012-10-23 14:59 169 查看
在写C代码的时候,经常需要在头文件中包含有些预定义的信息。比如一些结构体的声明,外部变量,函数的声明等。

有时候觉得有必要在头文件中定义一些变量,这样在源文件中就不需要定义了。但是这样做,有很大的问题。

比如

//test.h
1 #ifndef _TEST_H
2 #define _TEST_H
3 int x;
4 const char *name = "hhcn";
5 #endif
~


//test.c

#include "test.h"


//main.c
1 #include <stdio.h>
2 #include "test.h"
3
4 int main()
5 {
6     int j = x;
7     printf("j= %d\n", j);
8
9 const   char *p = name;
10     printf("%s\n", p);
11
12     return 0;
13 }
~
这样,编译的时候,都通过了,但是链接的时候,会报

cc -c -o main.o main.c

cc -c -o test.o test.c

gcc main.o test.o -o test

test.o:(.data+0x0): multiple definition of `x'

main.o:(.data+0x0): first defined here

test.o:(.data+0x4): multiple definition of `name'

main.o:(.data+0x4): first defined here

collect2: ld returned 1 exit status

make: *** [all] 错误 1

你或许会认为,x我没有在其他地方定义啊!字符串name也是一个常量,怎么就会报重复定义呢?

其实,在test.c中包含了test.h,里面定义了x和name,main.c中也是这样。于是在链接的时候,不知道该用哪一个定义了。

正确的做法应该是只在头文件中声明,而真正的定义放到源文件中,这样不管哪个源文件包含了头文件,都不会有问题,因为定义的地方只有一个,链接的时候会找到的。

如果你真的认为很有必要在头文件中进行定义变量,那么就在前面加上static吧。起码可以保证你编译,链接的时候不出错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: