使用下面代码下载gcc32位库
sudo apt-get install gcc-multilib g++-multilib module-assistant
1.将C代码编译成汇编代码:
C语言代码:
#include <stdio.h> extern int B(); int A(int x,int y) { int d,e,f; d = 4;e = 5;f = 6; f = B(d,e); }
汇编代码:
2.用汇编语言实现函数
获取CPU寄存器
main.c
#include <stdio.h> extern int get_ebp(); extern int get_esp(); int main() { int ebp, esp; ebp = get_ebp(); esp = get_esp(); printf("ebp=%8x esp=%8x\n",ebp,esp); }
s.s
.section .text .global get_esp, get_ebp get_esp: movl %esp, %eax ret get_ebp: movl %ebp, %eax ret
运行截图:
3.用汇编编写mysum函数
mysum.s
.text .global mysum,printf mysum: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax addl 12(%ebp), %eax movl %ebp, %esp pop %ebp ret
mysum.c
#include <stdio.h> extern int mysum(int a, int b); int main() { int a,b,c; a = 123; b = 456; c = mysum(a,b); printf("c = %d\n",c); }
运行截图:
3.从汇编调用C函数
b.c
#include <stdio.h> int a,b; extern int sub(); int main() { a = 100; b = 200; sub(); }
b.s
.text .global sub, a, b, printf sub: pushl %ebp movl %esp, %ebp pushl b pushl a pushl $fmt call printf addl $12, %esp movl %ebp,%esp pop %ebp ret .data fmt: .asciz "a = %d b = %d\n"
运行截图: