假设我们写了一个C代码文件 code.c包含下面代码:
int accum = 0;
int sum(int x, int y)
{
int t = x + y;
accum += t;
return t;
}
这是用echo命令输入源码的效果,简单的就是最好的:)
一、查看GCC生成的汇编代码
在命令行上用“-S”选项,就能看到C编译器产生的汇编代码:
gcc -S code.c (注意:这里是大写的-S,如果用小写gcc会说找不到main函数)
这段汇编代码没有经过优化:
.file "code.c"
.globl _accum
.bss
.align 4
_accum:
.space 4
.text
.globl _sum
.def _sum; .scl 2; .type 32; .endef
_sum:
pushl %ebp
movl %esp, %ebp
subl $4, %esp # 为局部变量t在栈帧上分配空间
movl 12(%ebp), %eax # %eax <- y
addl 8(%ebp), %eax # %eax <- x + y
movl %eax, -4(%ebp) # t <- x +y
movl -4(%ebp), %eax # %eax <- t
addl %eax, _accum # _accum <- t + _accum
movl -4(%ebp), %eax # %eax <- t
leave # 平衡堆栈: %esp <- %ebp , popl %ebp
ret
.globl _accum
.bss
.align 4
_accum:
.space 4
.text
.globl _sum
.def _sum; .scl 2; .type 32; .endef
_sum:
pushl %ebp
movl %esp, %ebp
subl $4, %esp # 为局部变量t在栈帧上分配空间
movl 12(%ebp), %eax # %eax <- y
addl 8(%ebp), %eax # %eax <- x + y
movl %eax, -4(%ebp) # t <- x +y
movl -4(%ebp), %eax # %eax <- t
addl %eax, _accum # _accum <- t + _accum
movl -4(%ebp), %eax # %eax <- t
leave # 平衡堆栈: %esp <- %ebp , popl %ebp
ret
下面是使用“-O2”选项开启二级优化的效果:
gcc -O2 -S code.c
.file "code.c"
.globl _accum
.bss
.align 4
_accum:
.space 4
.text
.p2align 4,,15 # 使下一条指令的地址从16的倍数处开始,
.globl _sum # 最多浪费15个字节
.def _sum; .scl 2; .type 32; .endef
_sum:
pushl %ebp # 保存原%ebp
movl %esp, %ebp
movl 12(%ebp), %eax # %eax <- y
movl 8(%ebp), %edx # %edx <- x
popl %ebp # 恢复原%ebp
addl %edx, %eax # %eax <- x + y
addl %eax, _accum # _accum <- _accum + x + y
ret
.globl _accum
.bss
.align 4
_accum:
.space 4
.text
.p2align 4,,15 # 使下一条指令的地址从16的倍数处开始,
.globl _sum # 最多浪费15个字节
.def _sum; .scl 2; .type 32; .endef
_sum:
pushl %ebp # 保存原%ebp
movl %esp, %ebp
movl 12(%ebp), %eax # %eax <- y
movl 8(%ebp), %edx # %edx <- x
popl %ebp # 恢复原%ebp
addl %edx, %eax # %eax <- x + y
addl %eax, _accum # _accum <- _accum + x + y
ret
GCC产生的汇编代码有点难读,它包含一些我们不关心的信息。所有以 "." 开头的行都是指导汇编器和链接器的命令,称为“汇编器命令”。