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

标签 c assembly mips

我试图从汇编文件调用在 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= %d\nf= %d\n", 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, ($t6)
    add $t6, $t6, 4
    lw $a2, ($t6)
    add $t6, $t6, 4
    lw $a3, ($t6)
    add $t6, $t6, 4
    lw $t3, ($t6)
    jal PolyCalc

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

    lw $ra, 0($sp)
    addi $sp, $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,$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 的 [limited] 范围,链接器可能会将其放置得太远,因此您可能必须将其替换为:

la $t0,BubbleSort
jalr $t0

关于c - MIPS - 在汇编代码中调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980971/

相关文章:

c - 如何获取https网站证书公钥

c++ - C程序读取2个字符串之间的数据

c++ - 如何在 Microsoft Visual Studio C/C++ 编译器中关闭位置无关代码编译?

c - C语言嵌入ARM汇编

c - MIPS/C 中的钻石排序

c - 从命令行参数分配数组

c - scanf 中 double 的格式说明符

optimization - 防止 clang 用库调用替换我的代码

c - 为什么 .bss 显式地将全局变量初始化为零?

java - 将值(value)存储为空头