C语言头文件知多少
本菜鸟第一次在CSDN上写博客,自知表述和写作能力一般,存在表述或者理解有错误的地方,欢迎各位大牛斧正。
C程序有如下两种头文件包含方式:
#include "c_header_find.h"
#include <c_header_find.h>
这里提几个问题,如果你能清晰肯定的给出答案,那么请无情的飘过。
1. 上面两种头文件包含方式的区别是什么?
2. 编译器在预处理阶段在哪些目录下搜索头文件?
3. 搜索头文件的顺序是什么样的?
1. 测试环境及GCC编译器信息
1.1 测试环境
[root@localhost ccode]# uname -s
Linux
[root@localhost ccode]# uname -m
x86_64
[root@localhost ccode]# uname -r
2.6.32-431.el6.x86_64
1.2 GCC编译器
[root@localhost ccode]# gcc -v
Using built-in specs.
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr--mandir=/usr/share/man --infodir=/usr/share/info--with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap--enable-shared --enable-threads=posix --enable-checking=release--with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions--enable-gnu-unique-object--enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk--disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre--enable-libgcj-multifile --enable-java-maintainer-mode--with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib--with-ppl --with-cloog --with-tune=generic --with-arch_32=i686--build=x86_64-redhat-linux
Thread model: posix
gcc version 4.4.7 20120313 (Red Hat4.4.7-4) (GCC)
2. 测试方法和步骤
2.1 步骤一
在linux下创建一个测试目录,这里以/home/chenqianwu/ccode目录为例,在该目录下创建一个c源文件“c_header_find.c”和一个头文件“c_header_find.h”。
c_header_find.c内容如下:
#include <stdio.h>
#include "c_header_find.h"
int main(void)
{
printf("header:%s\n", header);
return 0;
}
c_header_find.h内容如下:
#define header "current path"
2.2 步骤二
将c_header_find.h拷贝一份到/opt目录下,并修改其内容为如下:
#define header "-I path"
2.3 步骤三
在opt目录下创建include目录,将c_header_find.h拷贝一份到/opt/include目录下,并修改其内容为如下:#define header "C_INCLUDE_PAT";同时执行“export C_INCLUDE_PATH=/opt/include/”命令。
2.4 步骤四
使用命令“gcc -g -I/opt -o c_header_findc_header_find.c”编译程序,然后执行程序,输出结果是“header:current path”。
删除/home/chenqianwu/ccode目录下的c_header_find.h文件,重新编译程序,然后执行程序,输出结果是“header:-Ipath”
删除/opt目录下的c_header_find.h文件,重新编译程序,然后执行程序,输出结果是“header:C_INCLUDE_PAT”
3. 结论
对于用#include "c_header_find.h"而不是#include <c_header_find.h>这种方式包含的头文件,编译器在预处理阶段,头文件的搜索目录及搜索顺序满足下面的规则:
1. 在当前目录查找
2. 如果当前目录没有,则到编译时用“-I”选项指定的目录查找。
3. 如果“-I”指定的目录没有,则到环境变量“C_INCLUDE_PAT”指定的目录去查找。
4. 如果都找不到,则到编译器预设的目录去查找,编译器预设的目录是什么?这里给读者留一点思考的实践的空间。
如果把#include "c_header_find.h"改为#include <c_header_find.h>又是什么情况呢?这里也留给读者自己去验证。