C 語言的函數呼叫如何轉為組合語言

高等 C 語言

簡介

字串

指標與陣列

函數

結構

物件導向

記憶體

檔案

錯誤處理

巨集處理

C 與組合語言

資料結構

動態字串

動態陣列

鏈結串列

雜湊表

開發環境

Make

Cygwin

MinGW

DevC++

wxDevC++

編譯器

gcc 編譯器

TinyCC 編譯器

LCC 編譯器

應用主題

CGI 程式

GNU 程式

視窗程式

影像處理

練習題

訊息

相關網站

參考文獻

最新修改

簡體版

English

C 語言的函數呼叫如何轉換為組合語言呢?

答案是利用堆疊,但是卻不是用 PUSH,而是直接寫入參數到相對於堆疊指標的某個位址。

請看下列範例!

範例:ccall.c

int g(int x, int a) {
    return x+a;
}
 
int f(char *s, int i, char c) {
    g(i, 3);
    return 0;
}
 
int main() {
    int ret = f("abc", 1, 'x');
    return 1;
}

範例:ccall.s

指令:gcc -S ccall.c -o ccall.s

    .file    "ccall.c"
    .text
.globl _g
    .def    _g;    .scl    2;    .type    32;    .endef
_g:
    pushl    %ebp # 保存舊的 Frame Pointer
    movl    %esp, %ebp # 設定新的 Frame Pointer
    movl    12(%ebp), %eax # eax = x
    addl    8(%ebp), %eax # eax = eax+a
    popl    %ebp # 恢復舊的 Frame Pointer
    ret        # 返回上一層
.globl _f
    .def    _f;    .scl    2;    .type    32;    .endef
_f:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $12, %esp
    movl    16(%ebp), %eax
    movb    %al, -1(%ebp)
    movl    $3, 4(%esp)   # 4(%esp) 值為 3 => 透過 4(%esp) 傳給 a
    movl    12(%ebp), %eax
    movl    %eax, (%esp)  # 12(%ebp) 值為 i => 透過 (%esp) 傳給 x
    call    _g            # g(i,3) = g(x=esp[0..3], a=esp[4..7])
    movl    $0, %eax
    leave
    ret
    .def    ___main;    .scl    2;    .type    32;    .endef
    .section .rdata,"dr"
LC0:
    .ascii "abc\0"
    .text
.globl _main
    .def    _main;    .scl    2;    .type    32;    .endef
_main:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $24, %esp
    andl    $-16, %esp
    movl    $0, %eax
    addl    $15, %eax
    addl    $15, %eax
    shrl    $4, %eax
    sall    $4, %eax
    movl    %eax, -8(%ebp)
    movl    -8(%ebp), %eax
    call    __alloca
    call    ___main
    movl    $120, 8(%esp)
    movl    $1, 4(%esp)
    movl    $LC0, (%esp)
    call    _f
    movl    %eax, -4(%ebp)
    movl    $1, %eax
    leave
    ret

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License