现在的位置: 首页 > 综合 > 正文

ARM汇编语言与C/C++的混合编程

2014年11月13日 ⁄ 综合 ⁄ 共 1529字 ⁄ 字号 评论关闭

 

ARM公司不生产芯片,而是出售核(如ARM9)给硬件厂商,硬件厂商添加一些外围器件,就成了芯片(s3c2440)

   

ARM汇编语言与C/C++的混合编程

  C/C++代码中嵌入汇编指令

 

在C/C++中使用内嵌的汇编指令语法格式:

使用关键字_ _asm来标识一段汇编指令程序

_ _asm

{

    汇编语言程序

   ~~~~~~~~~~

    汇编语言程序

}

例C1.C

#include <stdio.h>

void my_strcpy(const char *src, char *dest) 

{

   char ch;

     _ _asm

    { 

        loop:

        ldrb ch, [src], #1

        strb ch, [dest], #1

        cmp ch, #0

        bne loop

    } 

}

 

 

int main()

 

{

 

    char *a = "forget it and move on!";

 

    char b[64];

 

    my_strcpy(a, b);

 

    printf("original: %s", a);

 

    printf("copyed: %s", b);

 

    return 0;

 

}

 

 

二在汇编程序和C/C++的程序之间进行变量的互访

 

c2.c

#include <stdio.h>

 

/*定义全局变量gVar_1*/

int gVar_1 = 12;  

 

extern asmDouble(void);

 

int main()

{

 

    printf("original value of gVar_1 is: %d", gVar_1);

 

    asmDouble();

 

    printf(" modified value of gVar_1 is: %d", gVar_1);

 

    return 0;

 

}

 

s2.S

AREA asmfile, CODE, READONLY

 

EXPORT asmDouble

 

IMPORT gVar_1     //汇编程序导入便可访问这个变量

 

asmDouble

 

    ldr r0, =gVar_1

 

    ldr r1, [r0]

 

    mov r2, #2

 

    mul r3, r1, r2

 

    str r3, [r0]

 

    mov pc, lr

 

END

 

 

  C/C++调用汇编函数

在c中声明函数原型,并加上extern关键字

在汇编中用EXPORT导出函数名,使用mov pc , lr返回,然后在c中使用该函数。

 

C3.C

#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;

}

 

S3.S

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

 

四 汇编调用C

 

需要在汇编中用IMPORT对应的c函数名

 C4.C

int cFun(int a, int b, int c)

{

    return a + b + c;

}

 

C4.S

EXPORT asmfile

AREA asmfile, CODE, READONLY

IMPORT cFun

ENTRY

    mov r0, #11

    mov r1, #22

    mov r2, #33

    BL cFun

END

 

抱歉!评论已关闭.