如何在汇编程序中调用外部函数?

时间:2016-09-09 23:57:47

标签: linux assembly hyperlink ld libc

我尝试在汇编代码中使用外部函数:

        .section    .rodata
    .LC0:
        .string "My number is: %lld"
        .text
        .globl  start
    start:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $16, %rsp
        movq    $12345, -8(%rbp)
        movq    -8(%rbp), %rax
        movq    %rax, %rsi
        movl    $.LC0, %edi
        movl    $0, %eax

        call    printf   # my external function

        # exit-syscall
        mov $1, %eax
        mov $0, %ebx
        int $0x80

我汇集并与之联系:

as -o myObjfile.o mySourcefile.s
ld -e start -o myProgram -lc myObjfile.o

可执行文件是构建的,但它不会运行,所以它有什么问题?

1 个答案:

答案 0 :(得分:-3)

如果我理解你要调用的函数是否在C库中,你可以将它声明为外部函数。

    .section    .rodata
.LC0:
    .string "My number is: %lld"
    .text
    .extern printf    #declaring  the external function
    .globl  start
start:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movq    $12345, -8(%rbp)
    movq    -8(%rbp), %rax
    movq    %rax, %rsi
    movl    $.LC0, %edi
    movl    $0, %eax

    call    printf   # my external function

    # exit-syscall
    mov $1, %eax
    mov $0, %ebx
    int $0x80

如果这不起作用,请尝试使用stdlib.h明确链接