使用 printf 声明变量的顺序(程序集)

Order of declared variables with printf (assembly)

这是我的工作代码:

.section .data
prompt:
    .asciz "Please input value:\n"
input:
    .asciz "%d"
output:
    .asciz "output: %d\n"
integer:
    .int
.section .text
.globl  main
main:
    nop

    pushl $prompt
    call printf
    addl , %esp

    pushl $integer
    pushl $input
    call scanf
    addl , %esp

    movl integer, %ecx
    pushl %ecx
    pushl $output
    call printf
    add , %esp

    pushl [=10=]
    call exit

为什么如果我改变顺序:

input:
    .asciz "%d"
output:
    .asciz "output: %d\n"
integer:
    .int

至(其中 integer 高于其 input

integer:
    .int
input:
    .asciz "%d"
output:
    .asciz "output: %d\n"

...然后它不再打印出您扫描的整数?是不是因为我们先引用了$integer,才压入栈?

您需要为 .int 实际指定一个值,否则它不会执行任何操作。因此,在第二种情况下,您的整数(4 个字节)也与 inputoutput 的开头重叠。假设您输入的数字的最高有效字节为零(即任何小于 2^24 的非负数),您将有效地将输出字符串截断为零长度。

要修复它,您只需执行 .int 0 或在 .bss 部分声明您的整数,例如使用 .lcomm integer, 4.