Android 的 ARM 汇编器中对 'printf' 的未定义引用

Undefined reference to 'printf' in ARM assembler for Android

我正在尝试按照我在博客上找到的示例进行操作。

androideabi好像不能直接在汇编代码级别调用printf(可能是我编译的时候少了一个flag?)。

我是运行这些命令:

arm-linux-androideabi-as -o fib.o fibonacci.s
arm-linux-androideabi-ld --sysroot $env:SYSROOT -s -o fib fib.o
fib.o(.text+0x8): error: undefined reference to 'printf'

我从汇编代码中得到一个未定义的引用。

如果它真的成功了,那就太好了。如果有人想分享他们在底层编程方面的出色知识,我当然愿意接受替代解决方案!

这个问题有什么建议吗?代码如下:

.syntax unified

.equ maxfib,4000000

previous .req r4
current  .req r5
next     .req r6
sum      .req r7
max      .req r8
tmp      .req r9

.section .rodata
 .align 2
fibstring:
 .asciz "fib is %d\n"
sumstring:
 .asciz "%d\n"

len = . - sumstring
.text
 .align 2
 .global main
 .extern printf
 .type main, %function
main:
 stmfd sp!, {r4-r9, lr}
 ldr max,   =maxfib
 mov previous, 1
 mov current, 1
 mov sum, 0

loop:
 cmp current, max
 bgt last

 add next, current, previous

 movs tmp, current, lsr 1      @ set carry flag from lsr - for the odd-valued terms
                               @ we discard the result of the movs and are only interested
                               @ in the side effect of the lsr which pushes the lower bit
                               @ of current (1 for odd; 0 for even) into the carry flag
                               @ movs will update the status register (c.f. mov which will not)
 addcc sum, sum, current       @ we add current to the sum ONLY when cc (carry clear) is true
                               @ these are even-valued fibonacci terms

 mov previous, current
 mov current, next
 b loop

last:
 mov r1, sum
 ldr r0, =sumstring            @ store address of start of string to r0
 bl         printf

 mov r0, 0
 ldmfd sp!, {r4-r9, pc}
 mov r7, 1                     @ set r7 to 1 - the syscall for exit
 swi 0                         @ then invoke the syscall from linux

您需要 link 到 C 运行时库 aka libc,才能获得 printf。您可以在 linking 命令的末尾添加 -lc,或者使用 gcc 前端而不是直接使用 ld

即,要么这样做:

arm-linux-androideabi-ld --sysroot $env:SYSROOT -s -o fib fib.o -lc

或者这样:

arm-linux-androideabi-gcc --sysroot $env:SYSROOT -Wl,-s -o fib fib.o

使用gcc -o fib fib.o 而不是 ld -o fib fib.o