linux 使用printf GAS打印整数

zpqajqem  于 12个月前  发布在  Linux
关注(0)|答案(1)|浏览(151)

在下面的程序中,我试图打印出从2到n的偶数,n作为函数void even(int n)的参数传入。我有一个不同的main. c文件来调用这个函数。

.extern printf
.section .data
format:
    .asciz "%d\n"

.section .text
.global even
even:
    cmpl $2, %edi #compare n to 2
    jl less_than_two #if n < 2 then jump to less_than_two
#if not, start from 2
    movl $2, %ebx           # start from 2

loop:
    # print the number
    movl $format, %esi # the string format of printf is in esi
    movl %ebx, %edi # the first argument of printf is in edi
    subq $8, %rsp # make room on the stack for the argument
    movl %edi, (%rsp) # push the argument onto the stack
    call printf
    addq $8, %rsp # clean up the stack

    addl $2, %ebx #add 2 to ebx
    cmpl %ebx, %edi # compare n with ebx
    jl end # if n < ebx then jump to end
    jmp loop #else continue to print

less_than_two:
    movl $format, %esi
    xorl %edi, %edi
    subq $8, %rsp # make room on the stack for the argument
    movl %edi, (%rsp) # push the argument onto the stack
    call printf
    addq $8, %rsp # clean up the stack
    ret

end:
    ret

字符串
当我尝试在Linux终端上编译并运行它时,我得到的结果是:分段错误(核心转储)。

ttygqcqt

ttygqcqt1#

在x86_64 Linux中,参数在寄存器中传递,而不是在堆栈中传递,因此打印代码应该更像

# print the number
    leaq format(%rip), %rdi   # the string format of printf is in rdi
    movl %ebx, %esi           # the first int argument of printf is in esi
    xor %eax, %eax            # set %al to 0 for no args in xmm regs
    call printf

字符串
the ABI spec的所有血淋淋的细节

相关问题