|
|
|
|
 头文件中的一个问题 - czijian [ 2005-02-25 16:27 | 1,643 byte(s)]
 Re: 头文件中的一个问题 - Atu [ 2005-02-25 17:14 | 721 byte(s)]
|
|
|
|
[Original]
[Print]
[Top]
|
我在实际的项目中用到了一些全局变量,总让我不踏实。这些变量主要是在头文件中给出的
下面是个例子。
//file.h
1
2
3 int whole;
4 typedef struct
5 {
6 int a;
7 char b;
8 } struct_s;
9
10 void f(struct_s*);
//file1.h
1 #include <stdio.h>
2 #include "file.h"
3
4 int main()
5 {
6 struct_s a={1,'a'};
7 struct_s* ptr=&a;
8
9 f(ptr);
10 printf("the whole's value is %d
",whole);
11 return 0;
12 }
//file2.h
1 #include <stdio.h>
2 #include "file.h"
3
4 //whole=2;
5
6 void f(struct_s* ptr)
7 {
8 whole=2;
9 printf("the struct's value is %d and %c
",ptr->a,ptr->b);
10 return;
11 }
看我的file.h的第3行,我定义了一个whole(应该不能算是声明吧)。
而file1.h和file2.h都包含了这个whole,那么怎么不会出现重复定义的警告,
编译都通过,而且工作的很好。这个全局变量让我很不舒服,我的希望是不要
在头文件中出现这种变量的定义,但是多个文件又要同时访问这个变量。希望
大家给我这个井底之蛙指点。
|
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
为什么不会出现重复定义的错误,我暂时说不清楚。
可以参考一下<<C/C++深层探索>>这本书,它详细讨论了C中声明和定义的关系。
而且也讨论了你的这种情况。
大概意思是:声明和定义在某种情况下可以自动转换。
如果你用C++编译,就错了了: multiple definition of `whole'
而C就可以。
给你一个建议吧:
在a.h中写成
extern int whole;
它将作为一个声明,在每个你要使用这个变量的文件里面#include "a.h"
声明可以重复。
在一个合适的文件(.c或.cc)里,写
int whole;
这样应该就对了。
试试吧
|
|
|
[Original]
[Print]
[Top]
|
|
|