程序编译
从源文件到可执行文件中经历四个过程:
1.预编译:将原文件中头文件展开,宏定义处理(就是对宏定义进行替换),生成.i文件,再不做其他处理。预编译处理好的文件为.i文件。
(Linux编译环境中执行代码 gcc -o text.i -E text.c)
2.汇编:对预编译处理好的.i文件进行语法检测,提示,生产.s文件,对其他错误不做检查。汇编处理好的文件为.s文件。
(Linux编译环境中执行代码gcc -o text.s -S text.i)
3.编译:对汇编处理好的.s文件进行编译,编译为机器能之间看得懂的语言,生成目标文件.o文件。编译好的文件为.o文件。
(Linux编译环境中执行代码gcc -o text.o -c text.s)
4.链接:让调用函数和调用的目标文件与主目标文件链接,生成可执行文件。该过程会对没有进行定义而调用的函数进行报错,前面的过程都不会进行此过程,所以不会有这样链接的报错。
(Linux编译环境中执行代码gcc -o text text.o)
text.c
#include <stdio.h>
#include "min.h"
#include "max.h"
#define A 100
void main()
{
int a = A;
printf("Hello C %d.\n",a);
}
min.h
int Min(int a, int b);
max.h
#ifndef __MAX_H_
#define __MAX_H_
int Max(int a, int b);
#endif /* __MAX_H_ */
min.c
#include"Min.h"
int Min(int a, int b)
{
return a > b ? b : a;
}
max.c
#include"Max.h"
int Max(int a, int b)
{
return a > b ? a : b;
}
预编译实例
将头文件展开,宏定义替换
min.i
int Min(int a, int b);
int Min(int a, int b)
{
return a > b ? b : a;
}
max.i
int Max(int a, int b);
int Max(int a, int b)
{
return a > b ? a : b;
}
text.i
......//#include <stdio.h>的展开
int Min(int a, int b);//#include "min.h"的展开
int Max(int a, int b);// #include "max.h"的展开
void main()
{
int a = 100;
printf("Hello C. %d\n",a);
}
汇编
语法检测,生成min.s,max.s,text.s文件
…
编译
编译成机器语言,生成min.o,max.o,text.o文件
…
链接
将min.o,max.o,text.o文件链接生成可执行文件text文件
…