在C中调用汇编文件中的函数,要做的主要工作有两个,一是在C 中声明函数原型,并加extern 关键字;二是在汇编中用EXPORT 导出函数名,并用该函数名作为汇编代码段的标识,最后用mov pc, lr 返回。然后,就可以在C 中使用该函数了。
EXTERN symbol 作用:在链接时,名称被解析为在其他对象文件中定义的符号。 该符号被当作程序地址。
在这里,C 和汇编之间的参数传递是通过ATPCS(ARM Thumb Procedure Call Standard)的规定来进行的。简单的说就是如果函数有不多于四个参数,对应的用R0-R3 来进行传递,多于4 个时借助栈,函数的返回值通过R0 来返回。
下面举例两个:
范例1:
#include <stdio.h>
extern void asm_strcpy(const char *src, char *dest);
int main()
{ const char *s = "seasons in the sun";
char d[32];
asm_strcpy(s, d);
printf("source: %s", s);
printf(" destination: %s",d);
return 0;
}
;asm function implementation
AREA asmfile, CODE, READONLY
EXPORT asm_strcpy
asm_strcpy
loop:
ldrb r4, [r0], #1
cmp r4, #0
beq over
strb r4, [r1], #1
b loop
over:
mov pc, lr
END
范例2:
AREA SCopy, CODE, READONLY
EXPORT strcopy
strcopy
; r0 points to destination string
; r1 points to source string
LDRB r2, [r1],#1 ; load byte and update address
STRB r2, [r0],#1 ; store byte and update address;
CMP r2, #0 ; check for zero terminator
BNE strcopy ; keep going if not
MOV pc,lr ; Return
END
#include <stdio.h>
extern void strcopy(char *d, const char *s);
int main()
{ const char *srcstr = "First string - source";
char dststr[] = "Second string - destination";
/* dststr is an array since we're going to change it */
printf("Before copying:\n");
printf(" '%s'\n '%s'\n",srcstr,dststr);
strcopy(dststr,srcstr);
printf("After copying:\n");
printf(" '%s'\n '%s'\n",srcstr,dststr);
return 0;
}