我试图提示用户输入两个整数,然后打印这两个整数的总和。我已经弄清楚如何打印一个整数n,但我无法打印第二个整数,m。
当我运行此代码时,它按预期工作,除了它只打印n的值。
以下是步骤和我的代码:
/* 1. Prompt the user to enter an integer
* 2. Read an integer from the keyboard into memory
* 3. Prompt the user to enter another integer
* 4. Read an integer from the keyboard into memory
* 5. Load the two integers into CPU registers
* 6. Add them together
* 7. Print the result
*/
.data
prompt: .asciz "Enter a number: " @ user prompt
.align 2
sformat:.asciz "%d" @ Format string for reading an int with scanf
.align 2
pformat:.asciz "The sum is: %d\n" @ Format string for printf
.align 2
n: .word 0 @ int n = 0
m: .word 0 @ int m = 0
.text
.global main
main: stmfd sp!, {lr} @ push lr onto stack
@ printf("Enter a number: ")
ldr r0, =prompt
bl printf
@ scanf("%d\0", &n)
ldr r0, =sformat @ load address of format string
ldr r1, =n @ load address of int n variable
bl scanf @ call scanf("%d", &n)
@ printf("Enter a number: ")
ldr r0, =prompt
bl printf
@ scanf("%d\0" &m)
ldr r0, =sformat @ load address of format string
ldr r2, =m @ load address of int m variable
bl scanf @ call scanf("%d", &m)
@ printf("You entered %d\n", n)
ldr r0, =pformat @ load address of format string
ldr r2, =m
ldr r2, [r2]
ldr r1, =n @ load address of int variable
ldr r1, [r1] @ load int variable
add r1, r2, r1
bl printf @ call printf("You entered %d\n", n)
ldmfd sp!, {lr} @ pop lr from stack
mov r0, #0 @ load return value
mov pc, lr @ return from main
.end
编辑:我改变了这段代码,使用r1而不是r2:
@ scanf("%d\0" &m)
ldr r0, =sformat @ load address of format string
ldr r2, =m @ load address of int m variable
bl scanf @ call scanf("%d", &m)
这有效,但我不明白为什么。
答案 0 :(得分:1)
您的修复工作正常,因为所有体系结构都遵循某种调用约定,其中寄存器映射到函数参数并返回值。在这种情况下,scanf
接受两个参数,因此根据ARM EABI calling convention ,第一个参数将在r0中,第二个参数在r1中。