gpt4 book ai didi

c - 将汇编语言与 c 链接起来

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:38 25 4
gpt4 key购买 nike

我对汇编语言很陌生,对 C 语言也很陌生。我看过一个示例,该示例创建了一个从 C 代码调用的函数,汇编代码有一个函数可以进行计算并返回值(这个是一个任务)C代码:

#include <stdio.h>

int Func(int);

int main()
{
int Arg;
Arg = 5;
printf("Value returned is %d when %d sent\n",Func(Arg), Arg);
}

汇编代码:

.global Func
Func: save %sp,-800, %sp
add %i0, -45 , %l0
mov %l0, %i0
ret
restore

它从 C 代码中获取值,将值与汇编代码中的数字相加,并输出新数字。我在很大程度上理解这个例子。我们的任务(修改代码):“编写一个 C 源文件,它使用 2 个参数 A 和 B 调用 Func1,以及包含两个方法 Func1 和 Func2 的汇编源文件。让 Func1 调用 Func2,就好像它是 Func2(Q) . Func2 应该将其输入参数加倍并将该加倍的值发送回 Func1。Func1 应该将值 2*A + 2*B 返回给 C main。我已经尝试过这个,并提出了这个解决方案(请原谅我,我今天是新手)

#include <stdio.h>

int Func1(int, int);
void Func2(int, int);
int main()
{
int Arg1 = 20;
int Arg2 = 4;
printf("Value returned is %d ",Func1(Arg1,Arg2));

}

程序集:

.global Func1
Func1: save %sp,-800, %sp
mov %l0, %i0
mov %l1, %i1
call Func2
nop
ret
restore

Func2: save %sp,-800, %sp
umul %i0, 2 , %l0
umul %i1, 2 , %l1
call Func1
nop

它不起作用,对此我一点也不感到惊讶。我敢肯定这段代码有很多问题,但是对这里发生的事情或我做错了什么进行彻底的解释会很有帮助。

最佳答案

我看得对吗:

In Func1, you call Func2
which calls Func1 again
which calls Func2 again
which calls Func1 again
which calls Func2 again
...
Stack overflow, resulting in bad memory access and segmentation fault

显然,不要那样做 :)。你到底想做什么?从 Func2 返回乘法结果?然后返回它,就像从 Func1 返回加法结果一样。

然后作业明确说:

call Func2 as though it were Func2(Q). Func2 should double its input argument and send that doubled value back

那么为什么要给 Func2 两个参数呢?如果我们假设有效分配,那么您可以对其进行小块处理,就像我引用的这篇文章一样。它说 Func2 需要 1 个参数,所以相信这一点并用一个参数制作 Func2,并且你完成了一个分配(然后如果结果证明 assignemnt 无效或试图欺骗你,你需要回到它,当然, 但上面很清楚)。


但是为了帮助你,你有工作代码,对吧?

.global Func
Func: save %sp,-800, %sp
add %i0, -45 , %l0
mov %l0, %i0
ret
restore

对于 Func2,您需要更改该代码,使其乘以 2,而不是加 -45?您是否尝试过将添加指令更改为:

imul  %i0, 2 , %l0  

(或 umul,但在您的 C 代码中您指定了 int 而不是 unsigned int,所以我认为它是有符号的...)。


我不会为您编写Func1,但您会看到如何获得输入,我认为这是正确的。然后你需要在返回之前在 %i0 中产生结果。分小步进行:首先制作 Func1,它只返回 %i0 + %i1,根本不调用 Func2。然后尝试 2 * %i0 + %i1,调用一次 Func2。然后最终编写请求版本的 2 * %i0 + 2 * %i1 调用 Func2 两次(或者对于更少和更简单的代码,提取公因子,所以你仍然需要调用Func2 一次)。

关于c - 将汇编语言与 c 链接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14575093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com