在本文中以一段汇编代码为例介绍一下在i386和x86_64汇编语言中调用C 函数的过程。样例代码在ubuntu12.04 i386 环境下调试通过。此外本文还介绍了在将这段样例代码移植到x86_64环境下应该注意的问题。
样例代码的作用是计算两个整数的除法,并通过C语言的printf函数打印计算结果。
.section .data
dividend:
.quad 8335
divisor:
.int 25
quotient:
.int 0
remainder:
.int 0
output:
.asciz "The quotient is %d, and the remainder is %d\n"
.section .text
.globl _start
_start:
movl dividend, %eax
movl dividend+4, %edx
divl divisor
movl %eax, quotient
movl %edx, remainder
pushl remainder
pushl quotient
pushl $output
call printf
add $12, %esp
pushl $0
call exit
编译过程如下:
lil@lil-kvm:~/assembly$as -o divtest.o divtest.s
lil@lil-kvm:~/assembly$ld --dynamic-linker /lib/ld-linux.so.2 -lc -o divtest divtest.o
其中-lc 选项表示需要连接libc.so库,--dynamic-linker /lib/ld-linux.so.2 也必须指定,否则即使连接未报错,也会在运行时出现
bash: ./divtest: No such file or directory 错误。
编译后运行