As you feared, movq %rcx, %rsi
is not correct. You need to pass a pointer to memory. Registers are not part of the memory address space and thus you can't have pointers to them. You need to allocate storage either globally or locally. Incidentally, you should not put your data (especially writable) into the default .text
section, as that is intended for code and is typically read-only. Also, calling convention usually mandates 16 byte stack pointer alignment, so you should take care of that too.
.globl main
main:
push %rbp
mov $0, %eax
leaq f(%rip), %rdi
leaq x(%rip), %rsi
call scanf
pop %rbp
ret
.data
f: .string "%d"
x: .long 0
(If your environment expects a leading underscore on symbols, then use _main
, and probably _scanf
.)
There are actually 3 choices for putting addresses of symbols / labels into registers. RIP-relative LEA is the standard way on x86-64. How to load address of function or label into register in GNU Assembler
As an optimization if your variables are in the lower 4GiB of the address space, e.g. in a Linux non-PIE (position-dependent) executable, you can use 32-bit absolute immediates:
mov $f, %edi
mov $x, %esi
movq $f, %rdi
would use a 32-bit sign-extended immediate (instead of implicit zero-extension into RDI from writing EDI), but has the same code-size as a RIP-relative LEA.
You can also load the full 64 bit absolute address using the mnemonic movabsq
. But don't do that because a 10-byte instruction is bad for code-size, and still needs a runtime fixup because it's not position-independent.
movabsq $f, %rdi
movabsq $x, %rsi
Upon request: using a local variable for the output could look like:
subq $8, %rsp
xor %eax, %eax
leaq f(%rip), %rdi
movq %rsp, %rsi
call scanf
addq $8, %rsp
ret
scanf
is a standard library function, not a "system function". And for the second argument, it is expecting a memory address into which the result will be stored. You can mov a register value into RSI and expect it to store data in the previous register - that doesn't make any sense. Use LEA. - Jonathon Reinhart