gcc查看汇编代码

来源:互联网 发布:前瞻数据 编辑:程序博客网 时间:2024/04/30 14:42

1.gcc编译C语言程序

#include <stdio.h>intmain(){printf(“helloworld\n”);return0;}
把上面的程序存为hello.c,然后用gcchello.c -o hello,然后./hello,即可看到运行结果

2.使用gcc查看汇编代码

先写一个C程序,内容为:

#include <stdio.h>intsum(int x,int y){intt=x+y;returnt;}
使用gcc-S sum.c,会产生sum.s的文件,使用catsum.s打开文件,就可以看到汇编代码

sum:

pushl %ebp

movl %esp,%ebp

subl $16,%esp

movl 12(%ebp),%eax

movl 8(%ebp),%edx

addl %edx,%eax

movl %eax,-4(%ebp)

movl -4(%ebp),%eax

leave

ret

3使用gcc生成目标代码文件,gcc -c sum.c,在当前目录下会产生sum.o的二进制代码,如果要打开这个文件,可以使用反汇编器,objdump-d sum.o,输出结果为:

00000000<sum>:

0: 55 push %ebp

1: 89e5 mov %esp,%ebp

3: 83ec 10 sub $0x10,%esp

6: 8b45 0c mov 0xc(%ebp),%eax

9: 8b55 08 mov 0x8(%ebp),%edx

c: 01d0 add %edx,%eax

e: 8945 fc mov %eax,-0x4(%ebp)

11: 8b45 fc mov -0x4(%ebp),%eax

14: c9 leave

15: c3 ret

这里产生了22个顺序排列的十六进制字节值,左侧为机器执行代码,右边为等价的汇编语言。

4.生成可执行文件的方法

main()函数,

intmain()

{

return sum(1,2);

}

然后执行命令 gcc  -o obj sum.o main.c

使用命令objdump-d obj,输出为:

080483dc<sum>:

80483dc: 55 push %ebp

80483dd: 89e5 mov %esp,%ebp

80483df: 83ec 10 sub $0x10,%esp

80483e2: 8b45 0c mov 0xc(%ebp),%eax

80483e5: 8b55 08 mov 0x8(%ebp),%edx

80483e8: 01d0 add %edx,%eax

80483ea: 8945 fc mov %eax,-0x4(%ebp)

80483ed: 8b45 fc mov -0x4(%ebp),%eax

80483f0: c9 leave

80483f1: c3 ret

产生的目标文件汇编代码依然占用22个字节,但偏移地址与gcc-S sum.c的不同。


2 0