加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

MIPS – 在汇编代码中调用C函数

发布时间:2020-12-16 07:16:17 所属栏目:百科 来源:网络整理
导读:我试图从程序集文件中调用C文件中声明的函数,但我收到“非法指令”错误. 我的C代码: #include stdio.hint BubbleSort(int *v){ return 13;}int Run(int *,int *);int main(){ int vetor[] = {1,3,5,4,10},numTrocas = 0,res = 0; numTrocas = Run(vetor,res
我试图从程序集文件中调用C文件中声明的函数,但我收到“非法指令”错误.

我的C代码:

#include <stdio.h>

int BubbleSort(int *v){
    return 13;
}

int Run(int *,int *);


int main(){
    int vetor[] = {1,3,5,4,10},numTrocas = 0,res = 0;
    numTrocas = Run(vetor,&res);   
    printf("numTrocas= %dnf= %dn",numTrocas,res);
    return 0;
}

我的汇编代码:

.data 
.text 
.globl Run

Run:
    addi $sp,$sp,-8
    sw $ra,0($sp)
    sw $a0,4($sp)
    move $t4,$a1 #$t4 = $a1; address of variable res in C file
    move $t6,$a0 #$t6 = address of the first vector element

    lw $a0,($t6)
    add $t6,$t6,4
    lw $a1,4
    lw $a2,4
    lw $a3,4
    lw $t3,($t6)
    jal PolyCalc

    lw $a0,4($sp)
    jal BubbleSort #-> Illegal Instruction

    lw $ra,0($sp)
    addi $sp,8 
    jr $ra

PolyCalc: #This function calculates the result of the expression 5(V[0] + V[1])(V[2] ? 3xV[3]xV[4])
    li $s0,5             #$s0 = 5
    li $s1,3             #$s1 = 3
    add $t1,$a0,$a1      #t1=(x1+x2)
    mul $t1,$t1,$s0      #t1=5*(x1+x2)
    mul $t2,$a3,$t3      #$t2 = x4*x5
    mul $t2,$t2,$s1      #$t2 = 3*x4*x5
    sub $t2,$a2,$t2      #$t2 = (x3-3x4*x5)
    mul $t1,$t2      
    sw $t1,($t4) #Save the result on the address of $t4
    jr $ra

当我评论行jal BubbleSort并将随机值添加到$v0作为BubbleSort函数的返回时,我停止得到该错误并且程序正常工作.

有人可以在我的代码中找到错误吗?
谢谢

解决方法

为了更好地衡量,在你的asm文件中,你应该添加:

.extern BubbleSort

然后,jal BubbleSort应该正确重新定位.

但是,链接器可能会将它放在距离[有限]范围的jal太远的位置,因此您可能必须将其替换为:

la $t0,BubbleSort
jalr $t0

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读