内容来源: 牛客网
gcc编译过程
一般来讲,源文件是hello.c, 则使用命令:
gcc hello.c
就可以得到一个可执行文件.
但是这个过程不是一步做到的,实际上分为以下几步:
使用gcc分步得到可执行程序
源文件"hello.c"内容如下
#include<stdio.h>
int main(){
printf("hello\n");
return 0;
}
1. 预处理
事先写好了hello.c文件,现在需要对他预处理:
gcc hello.c -E -o hello.i
得到一个预处理后的文件"hello.i"
注意这里的后缀.i只是习惯,可以是其他任意文件名
打开后看到它内容有800多行,这里展示其中的一部分:
预处理主要是处理#include, #define等命令
2. 编译
输入命令:
gcc hello.i -S -o hello.s
得到文件hello.s, 可以看到里面均为汇编代码
.file "hello.c"
.section .rodata
.LC0:
.string "hello"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $.LC0, %edi
call puts
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.5 20150623 (Red Hat 4.8.5-44)"
.section .note.GNU-stack,"",@progbits
3. 汇编
gcc hello.s -c -o hello.o
生成一个二进制文件,不过暂时不能执行
4.链接
gcc hello.o -o hello.out
然后hello.out就可以执行啦