我在 Mac 上组装 x86 asm 代码时遇到问题。更具体地说,我收到错误。然而,当我在我的 Linux 计算机上汇编完全相同的源代码时,它就可以工作了。
我的情况:
我尝试使用以下命令:
as -maximum.s -o maximum.o
和
gcc -c maximum.s -o maximum.o
在这两种情况下,我都遇到了相同的错误:
maximum.s:1:15: error: unexpected token in '.section' directive
.section .data
^
maximum.s:5:15: error: unexpected token in '.section' directive
.section .text
^
我非常怀疑我的源代码有什么问题,因为它在 Linux 上编译得很好。但无论如何,这是我的完整源代码:
.section .data
data_items:
.long 3, 67, 34, 222, 45, 75, 54, 34, 44, 33, 22, 11, 66, 0
.section .text
.globl _start
_start:
movl $0, %edi
movl data_items(,%edi, 4), %eax
movl %eax, %ebx
start_loop:
cmpl $0, %eax
je loop_exit
incl %edi
movl data_items(,%edi, 4), %eax
cmpl %ebx, %eax
jle start_loop
movl %eax, %ebx
jmp start_loop
loop_exit:
movl $1, %eax
int $0x80
谢谢你
当我用
as
(clang-1500.1.0.2.5) 组装它时,我必须删除 .section
。例如,
.data
data_items:
.long 3, 67, 34, 222, 45, 75, 54, 34, 44, 33, 22, 11, 66, 0
.text
.globl _main
_main:
movq $0, %rbx # maximum in rbx
movq $0, %rcx # index in rcx
leaq data_items(%rip), %rsi # Load the address of data_items into %rsi
start_loop:
movl (%rsi, %rcx, 4), %eax # Load the value pointed to by si, offset by cx, into ax
cmpl $0, %eax
je loop_exit
incq %rcx
cmpl %ebx, %eax
jle start_loop
movl %eax, %ebx
jmp start_loop
loop_exit:
movq %rbx, %rdi
movq $0x2000001, %rax # 0x2000001 is the exit syscall number on macOS
syscall
FWIW,我已包含以下内容:
64 位寻址
syscall
0x2000001
我用
_main
代替了_start
。如果您确实想使用 _start
,则必须在链接时指定,例如,
ld -o maximum maximum.o -e _start
就我个人而言,拥有一系列
long
让我很痛苦,我会转向quad
,用l
演绎替换q
操作,用eax
/ebx
替换
rax
/
rbx
等等。话虽如此,您正在使用结果的返回码,而 IIRC 仅是 32 位,所以我没有在上面的代码片段中走这条路径。