参考 ARM官方文档实现 C inline assemly code, 运行环境 ARM DS-5 (arm6 compiler):
1. Writing inline assembly code http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.100748_0606_00_en/ddx1471430827125.html
#include int add(int i, int j)
{
int res = 0;
__asm ("ADD %[result], %[input_i], %[input_j]"
: [result] "=r" (res)
: [input_i] "r" (i), [input_j] "r" (j)
);
return res;
}int main(void)
{
int a = 1;
int b = 2;
int c = 0;
c = add(a,b);
printf("Result of %d + %d = %d\n", a, b, c);
}
2. Calling assembly functions from C and C++ http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.100748_0606_00_en/ddx1471430827125.html
helloARM.c
#include extern int myadd(int a, int b);
int main()
{
int a = 4;
int b = 5;
printf("Adding %d and %d results in %d\n", a, b, myadd(a, b));
return (0);
}
myadd.s
.globlmyadd
.p2align 2
.typemyadd,%functionmyadd:// Function "myadd" entry point.
.fnstart
addr0, r0, r1// Function arguments are in R0 and R1. Add together and put the result in R0.
bxlr// Return by branching to the address in the link register.
.fnend
【ARM C / C++ calling ASM】make all
Building file: ../src/helloARM.c
Invoking: Arm C Compiler 6
armclang --target=arm-arm-none-eabi -mcpu=cortex-a8 -mfpu=none -mfloat-abi=soft -marm -O0 -g -MD -MP -c -o "src/helloARM.o" "../src/helloARM.c"
armclang: warning: Your license for feature ult_armcompiler will expire in 26 days [-Wlicense-management]
Finished building: ../src/helloARM.c
Building file: ../src/myadd.s
Invoking: Arm Assembler 6
armclang --target=arm-arm-none-eabi -mcpu=cortex-a8 -mfpu=none -mfloat-abi=soft -marm -g -c -o "src/myadd.o" "../src/myadd.s"
armclang: warning: Your license for feature ult_armcompiler will expire in 26 days [-Wlicense-management]
Finished building: ../src/myadd.s
Building target: helloARM.axf
Invoking: Arm Linker 6
armlink --ro_base=0x80000000 --info=sizes -o "helloARM.axf"./src/helloARM.o ./src/myadd.o
3. 用汇编实现 strcpy helloARM.c
#include extern void strcopy(char* d, const char* s);
int main()
{
const char* srcstr = "First String";
char dststr[] = "Second String";
printf("Before strcopy: srcstr = %s, dststr = %s \n", srcstr, dststr);
strcopy(dststr, srcstr);
printf("After strcopy: srcstr = %s, dststr = %s \n", srcstr, dststr);
return (0);
}
scopy.s
.globl strcopystrcopy:
.fnstart
LDRB R2, [R1], #1
STRB R2, [R0], #1
CMP R2, #0
BNE strcopy
MOV pc, lr
.fnend
make all
Building file: ../src/helloARM.c
Invoking: Arm C Compiler 6
armclang --target=arm-arm-none-eabi -mcpu=cortex-a8 -mfpu=none -mfloat-abi=soft -marm -O0 -g -MD -MP -c -o "src/helloARM.o" "../src/helloARM.c"
Finished building: ../src/helloARM.c
Building file: ../src/scopy.s
Invoking: Arm Assembler 6
armclang --target=arm-arm-none-eabi -mcpu=cortex-a8 -mfpu=none -mfloat-abi=soft -marm -g -c -o "src/scopy.o" "../src/scopy.s"
Finished building: ../src/scopy.s
Building target: helloARM.axf
Invoking: Arm Linker 6
armlink --ro_base=0x80000000 --info=sizes -o "helloARM.axf"./src/helloARM.o ./src/scopy.o