C代码编译过程
假设下面是需要编译的hello.c
/code/chapter1/hello.c
#include <stdio.h> //1
int main(void){
printf("hello world!");//2
return 0;
}
C编译流程示意图
1.预处理(Pre-Processing)
hello.c中,在//2处调用了printf方法,而hello.c中并没有printf方法,那么程序是怎么找到这个方法的呢?
在编译过程中,预处理工具在遇到#include时,会将后面尖括号<filename>里面指定的文件直接插入到hello.c的最前面,filename在C语言的编译工具中,在stdio.h中存在printf方法,所以将stdio.h插入hello.c的最前面后,程序就能调用printf方法。
gcc -E -o hello.i hello.c
预处理之后生成的文件为hello.i,下面是部分内容:
/code/chapter1/hello.i
# 377 "c:\\mingw\\x86_64-w64-mingw32\\include\\stdio.h" 3
int __attribute__((__cdecl__)) fprintf(FILE * __restrict__ _File,const char * __restrict__ _Format,...);
int __attribute__((__cdecl__)) printf(const char * __restrict__ _Format,...);
int __attribute__((__cdecl__)) sprintf(char * __restrict__ _Dest,const char * __restrict__ _Format,...) ;
...
...
...
# 3 ".\\code\\chapter1\\hello.c"
int main(void){
printf("hello world!");
return 0;
}
从上面看到,预处理工具在c:\mingw\x86_64-w64-mingw32\include\stdio.h找到stdio.h,并将它插入到hello.c中。