适用于Android的ARM汇编程序中对'printf'的未定义引用

时间:2015-04-23 17:26:13

标签: android assembly android-ndk arm

我试图效仿我在博客上找到的一个例子。

似乎androideabi不能直接在汇编程序代码级别调用printf(也许我在编译时错过了一个标志?)。

我正在运行这些命令:

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

2 个答案:

答案 0 :(得分:2)

您需要链接到C运行时库libc,才能获得printf。您可以在链接命令的末尾添加-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

答案 1 :(得分:0)

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