c - X86-64 NASM 调用 extern c 函数

标签 c nasm x86-64 calling-convention abi

我对汇编很陌生,但懂一点 C。我正在玩外部函数调用,比如

extern _printf
str db "Hello", 0
push str
call _printf

但除了scanfprintf 外,找不到任何使用extern 函数的教程。如何调用 strcmp

最佳答案

这是我的答案。虽然它特定于 x86-64。请注意,将参数推送到函数时,通常将前 6 个放入寄存器 rdirsirdxrcxr8r9。其余的被插入堆栈。此规范称为 System V ABI(请注意,Windows 使用不同的约定,称为“Microsoft x64 调用约定”)。

    segment .data     ; or use .rodata for read-only data.
str1    db      "Hello", 0x0
str2    db      "Hellx", 0x0
fmt     db      "Comparison = %d", 0xa, 0x0

segment .text
    global main
    extern strcmp, printf
    default rel             ; RIP-relative addressing for [name] is what you want.

main:
    ; Create a stack-frame, re-aligning the stack to 16-byte alignment before calls
    push rbp
    mov rbp, rsp

    ; Prepare the arguments for strcmp.
    lea rdi, [str1]
    lea rsi, [str2]

    ; Call strcmp, return value is in rax.
    call strcmp

    ; Prepare arguments for printf.
    lea rdi, [fmt]
    mov esi, eax  ; int return value from strcmp -> 2nd arg for printf
    xor eax, eax  ; Indicate no floating point args to printf.

    ; Call printf
    call printf

    ; Return 0 (EXIT_SUCCESS), and destroy the stack frame.
    xor eax, eax
    leave            ; or just pop rbp because RSP is still pointing at the saved RBP
    ret

关于c - X86-64 NASM 调用 extern c 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240743/

相关文章:

c - x64 参数和返回值调用约定

c - 为什么只有注释更改的两个二进制程序在 gcc 中不完全匹配?

string - Nasm equ $-获得错误的长度

c - gcc内联汇编错误

assembly - 为什么 xmm 逻辑移位不起作用?

linux - 这个程序集如何不崩溃?

linux - 为什么在访问设置了 16 个最高有效位中的任何一个的内存时段错误地址为 NULL?

c - lpc1788 上的双缓冲

将所有数组元素复制到另一个数组中

c - Nativeint Bigarray 似乎未签名