- 论坛徽章:
- 0
|
本帖最后由 listenxu 于 2014-04-27 17:50 编辑
cxm240 发表于 2014-04-27 17:03 ![]()
所以说,头文件是不一定要包含的吗? 但是有一个问题是,为什么有时候不包含某些头文件又会报错呢?
----- ...
谢谢, 请问这种说法有出处吗?
我找到一片文章,说头文件主要是做类型检查,而不是为了编译是否可以通过,觉得有一定道理
http://blog.chinaunix.net/uid-24774106-id-3291005.html
但是貌似有些情况下,不包含头文件确实会报error; 按照你的说法,我对结构体做了测试;
======================================
创建文件helper.h, 声明结构体
void msg1(void);
typedef struct dint{
int a;
int b;
}dint;
然后再hello.c中定义结构体的实例dintx,并赋值:
#include <stdio.h>
//#include "helper.h"
int main()
{
struct dint dintx;
dintx.a = 1;
dintx.b = 2;
printf("Hello,Linuxprogramming world!\n");
msg1();
msg2();
return 0;
}
编译后报错:
error: storage size of ‘dintx’ isn’t known
将 //#include "helper.h" 注释“//”去掉,编译通过;
======================================
然后又做了如下测试:
======================================
添加文件helper2.h,加入一个变量:
int i;
void msg2(void);
在hello.c 中,对变量赋值
#include <stdio.h>
int main()
{
i = 1;
printf("Hello,Linuxprogramming world!\n");
msg1();
msg2();
printf("i=%d\n",i);
return 0;
}
编译,报如下错误
hello.c:6:3: error: ‘i’ undeclared (first use in this function)
然后将hello.c中include helper2.h,变成如下:
#include <stdio.h>
#include "helper2.h"
int main()
{
i = 1;
printf("Hello,Linuxprogramming world!\n");
msg1();
msg2();
printf("i=%d\n",i);
return 0;
}
编译即可通过;
=================================================
所以,综合起来看,结论如下
1, 如果仅引用了头文件中的函数,可以不include头文件,但是有风险,编译器不会对函数的参数做类型检查;
2, 如果引用了头文件中声明的变量,一定要include头文件
3, 如果引用了头文件中定义的非内部类型,如struct,一定要include头文件
|
|