现在的位置: 首页 > 综合 > 正文

C指针原理(4)

2014年01月02日 ⁄ 综合 ⁄ 共 1028字 ⁄ 字号 评论关闭

转自:http://blog.csdn.net/myhaspl/article/details/14140035

首先我们先用汇编编写一个helloworld,注意我们直接在汇编代码中调用C语言的printf函数将"hello,world\n" 输出在屏幕上。

  1. .section .data  
  2.   output:  
  3.   .asciz "hello,world\n"    
  4. .section .text  
  5.    .global  main  
  6.    main:  
  7.    push $output  
  8.    call printf  
  9.    addl $4,%esp  
  10.    push $0  
  11.    call exit  


上述代码中,

push $output将参数入栈,以便printf调用,

然后调用printf,printf会在栈中取出它需要的参数
2)我们直接使用GCC编译后运行 

deepfuture@ubu-s:~$ gcc -o  test test.s
deepfuture@ubu-s:~$ ./test
hello,world

 

3)那么调用C库函数所需要的参数入栈的顺序是什么?

再看一个例子

  1. .section .data  
  2.   myvalue:  
  3.      .byte 67,68,69,70,0  
  4.   mygs:  
  5.      .asciz "%s\n"  
  6.      
  7. .section .text  
  8. .globl main  
  9.    main:  
  10.     movl $myvalue,%ecx  
  11.     push %ecx  
  12.     push $mygs      
  13.     call printf  
  14.     push $0  
  15.     call exit  


67,68,69,70是C、D、E、F的ASCII码,0是字符串终结符
 这段代码的功能是输出“CEDF”,相当于下面的C代码

  1. #include <stdio.h>  
  2. int main( void )  
  3. {  
  4.      char myvalue[]={67,68,69,70,0};  
  5.      printf( "%s\n" ,myvalue);  
  6.      return 0;  
  7. }  


其中,后面的0表示字符串的终结符。

 

第一个参数最后一个入栈,按调用的相反顺序入栈

【上篇】
【下篇】

抱歉!评论已关闭.