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内联汇编