C指針原理(4)

轉自: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表示字符串的終結符。

 

第一個參數最後一個入棧,按調用的相反順序入棧


發佈了15 篇原創文章 · 獲贊 22 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章