一个 C/C++文件要经过预处理(preprocessing)、编译(compilation)、汇编(assembly)和链接(linking)等 4 步才能变成可执行文件。
体验一下上述的过程
#include <stdio.h>
#define MAX 20
#define MIN 10
//#define _DEBUG
#define SetBit(x) (1<<x)
int main(int argc, char* argv[])
{
printf("Hello World \n");
printf("MAX = %d, MIN = %d, MAX + MIN = %d\n", MAX, MIN, MAX + MIN);
#ifdef _DEBUG
printf("SetBit(5) = %d,SetBit(6) = %d\n",SetBit(5),SetBit(6));
printf("SetBit( SetBit(2) ) = %d\n",SetBit( SetBit(2) ));
#endif
return 0;
}
gcc -o hello hello.c -v
预处理:(查找头文件,展开宏) .c -> .i
1.查找头文件
#include “…” search starts here:
#include <…> search starts here:
/usr/lib/gcc/x86_64-linux-gnu/7/include
/usr/local/include
/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
/usr/include/x86_64-linux-gnu
/usr/include
编译:.i -> .s
cc1 hello.c -o /tmp/ccuVv7YJ.s
汇编:.s -> .o
as -v --64 -o /tmp/cceDi2sF.o /tmp/ccuVv7YJ.s
链接
把各种 .o
文件链接成 .elf
collect2 -o hello /tmp/cceDi2sF.o
可以手工执行以下命令体验一下:
预处理:
gcc -E -o hello.i hello.c
编译:
gcc -S -o hello.s hello.i
汇编:
gcc -c -o hello.o hello.s
链接:
gcc -o hello hello.o
注意:
语法错误是在编译过程中发现的,预处理过程中并未发现错误。
常见的编译选项
常用选项 | 描述 |
---|---|
-E | 预处理,开发过程中想要快速确定某个宏可以使用 “-E -dM” |
-c | 把预处理,编译,汇编都做了,但是不链接 |
-o | 指定输出文件 |
-l | 指定头文件目录 |
-I | 指定链接哪一个库文件 |