循序渐进,学习开发一个RISC-V 上的操作系统 练习5.9

ch5.9嵌入式汇编(C语言)

题目

在 C 函数中嵌入汇编,实现 foo 函数中的 c = a * a + b * b; 这句 c 语言的同等功能。

答案

int foo(int a, int b)
{
    int c;
#define USING_ASM_CODE
#ifdef  USING_ASM_CODE
    asm volatile(
    "mul %[sum],%[arg1],%[arg1];"
    "mul %[arg2],%[arg2],%[arg2];"
    "add %[sum],%[sum],%[arg2];"
    :[sum]"=r"(c)
    :[arg1]"r"(a),[arg2]"r"(b)
    );
#else
    c = a * a + b * b;
#endif
    return c;
}

test.s 直接使用call foo

# ch5.9 test
# Format:
# 在 C 函数中嵌入⼀段汇编,实现 foo 函数中的 c = a * a + b * b; 这句 c 语⾔的同等功能。
# Description:
        .text                   # Define beginning of text section
        .global _start          # Define entry _start
        .global foo             # Define c function foo

_start:
    la sp, stack_start
    li a0, 3
    li a1, 4
    call foo

stop:
        j stop                  # Infinite loop to stop execution
    nop             #
stack_end:
    .rep 100
    .long 0
    .endr
stack_start:
    .end                        # End of file

参考连接:
https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
riscv下的GCC内联汇编

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值