gcc内嵌汇编调用C函数

C样式的函数使用堆栈传递输入值;C库函数也是如此;所有输入参数都要放入堆栈中,顺序和函数中提到的顺序相反;汇编中压入栈中函数参数的顺序,和参数列表中函数出现的顺序相反;
代码如下所示:
C中函数printf的使用如下:

printf("The answer is %d\n", k);

汇编的版本是这样的:

pushl k
pushl $output
call printf
addl $8, %esp
在A&T汇编中,符号常数直接引用:

value: .long 0x12abcs32

mov value ,%ebx

指令执行的结果是将常数装入寄存器ebx

引用符号地址在符号前面加符号$,如“mov $value, %ebx”,则是将符号vlaue的地址装入寄存器ebx;

 pushl value
   pushl $v_string
   call printf
   addl $8, %esp
   nop
   nop
   pushl $value
   pushl $a_string
   call printf
   addl $8, %esp
上面代码的输出,为:

the value is 12345678
the address is 134513103

1.汇编调用C裤函数

.extern cstart 声明外部的C函数
.code32
.text
.global _start
_start:
   jmp Kernel_Start
KernelMessage:
   .asciz "hello world\n"
value:
   .long 0x12345678
v_string:
   .asciz "the value is %x\n"
a_string:
   .asciz "the address is %d\n"   
   
Kernel_Start:
   call cstart  #调用外部的C函数
   pushl $KernelMessage
   call printf  #调用C库函数
   addl $4, %esp
   pushl $0
   call fflush
   addl $4, %esp
   pushl value
   pushl $v_string
   call printf
   addl $8, %esp
   pushl $value
   pushl $a_string
   call printf
   addl $8, %esp
   movl $1, %eax
   movl $0, %ebx
   int $0x80
编译上述文件:

as assembly3.s -o assembly3.o

ld -dynamic-linker /lib/ld-linux.so.2 -lc assembly3.o -o assembly3

2.内嵌汇编调用自定义函数

#include <stdio.h>
#include <stdlib.h>
void print(char * pstr)
{
   printf("%s\n", pstr);
}
int main()
{
   char array[] = "I love you!\n";
   __asm__ __volatile__(
    "pushl %%ebx;" #变量进栈传递参数
    "call print;"  #调用c函数
    "addl $4, %%esp;"
    "nop"
    :
    : "b" (array) #代表输入,直接把变量的值赋值给EXB寄存器
   );
   return 0;
}



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值