在linux下使用gcc命令编译程序时,整个过程实际上在底层处理分为四个步骤--预处理/编译/汇编/连接
下面通过gcc的不同命令参数来拆解这四个步骤。
源代码:hello.c
#include <stdio.h>
#define PP printf
int main(int argc, char **argv) {
int a = 5;
PP("a = %d\n", a);
return 0;
}
1/预处理(C预处理器)
gcc -E hello.c -o hello.i//使用cpp命令
打开预处理后的文件hello.i,发现已经与源文件大有不同。主要区别我在注释处说明。
# 1 "hello.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "hello.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 28 "/usr/include/stdio.h" 3 4
....
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__));
# 936 "/usr/include/stdio.h" 3 4
# 2 "hello.c" 2 //以上是插入的stdio.h头文件内容
int main(int argc, char **argv) {
int a = 5;
printf("a = %d\n", a); //此处,宏定义PP被替换为printf
return 0;
}
2/编译(C编译器)
gcc -S hello.i -o hello.s//使用cc1命令
打开编译后的文件hello.s,所有语句均已替换为汇编语言,这对于嵌入式开发非常有用。
.file "hello.c"
.section .rodata
.LC0:
.st