关于“gdb”下尾部优化代码的疑问

发布于 2024-07-21 08:21:31 字数 1048 浏览 8 评论 0原文

考虑 C 中的尾递归阶乘实现:

#include <stdio.h>

unsigned long long factorial(unsigned long long fact_so_far, unsigned long long count, unsigned long long max_count){

if (max_count==0 || max_count==1 || count >= max_count)
        return fact_so_far;
else
{
        printf("%llu  %p \n", count, &factorial);
        return factorial(fact_so_far * count, ++count, max_count);
}

}


int main(int argc, char **argv)
{
        unsigned long long n;
        scanf("%llu", &n);
        printf("\n Factorial %llu \n",factorial(1,0,n));
        return 0;

}

我在“阶乘”中放置一个断点,然后在“gdb”下运行上述代码。 断点永远不会被命中。

假设它的尾部调用已优化(我已经使用 gcc -O2 编译了它),它应该至少命中断点一次,IIRC。

编辑:我在没有达到任何断点的情况下得到了最终结果。 例如,

(gdb) b factorial
Breakpoint 1 at 0x8048429: file factorial-tail.c, line 3.
(gdb) run
Starting program: /home/amit/quest/codes/factorial-tail 
5
0  0x8048420 
1  0x8048420 
2  0x8048420 
3  0x8048420 
4  0x8048420 

 Factorial 120 

Program exited normally.
(gdb) 

我哪里错了?

Consider a tail recursive factorial implementation in C:

#include <stdio.h>

unsigned long long factorial(unsigned long long fact_so_far, unsigned long long count, unsigned long long max_count){

if (max_count==0 || max_count==1 || count >= max_count)
        return fact_so_far;
else
{
        printf("%llu  %p \n", count, &factorial);
        return factorial(fact_so_far * count, ++count, max_count);
}

}


int main(int argc, char **argv)
{
        unsigned long long n;
        scanf("%llu", &n);
        printf("\n Factorial %llu \n",factorial(1,0,n));
        return 0;

}

I place a breakpoint in 'factorial' and I run the above under 'gdb'. The breakpoint is never hit.

Assuming that its tail call optimised (I have compiled it using gcc -O2), it should hit the breakpoint, atleast once, IIRC.

EDIT: I get the final result without hitting any breakpoint. For eg,

(gdb) b factorial
Breakpoint 1 at 0x8048429: file factorial-tail.c, line 3.
(gdb) run
Starting program: /home/amit/quest/codes/factorial-tail 
5
0  0x8048420 
1  0x8048420 
2  0x8048420 
3  0x8048420 
4  0x8048420 

 Factorial 120 

Program exited normally.
(gdb) 

Where am I going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

成熟稳重的好男人 2024-07-28 08:21:31

阶乘函数可能内联到 main 中。 如果发生这种情况,将会有第二个阶乘副本用于从其他 .c 文件进行调用; 那就是你的断点所在的地方。 尝试传递 -fno-inline。

It could be that the factorial function is inlined into main. If this happens, there will be a second copy of factorial used for calls from other .c files; that's where your breakpoint was. Try passing -fno-inline.

浅忆 2024-07-28 08:21:31

对我来说效果很好。 您是否打算在编译时使用 -g 标志来添加调试信息? 您还记得必须输入一个数字才能计算阶乘吗?

Works fine for me. You are membering to use the -g flag to add debug info when you compile? And you are remembering that you have to enter a number to calculate the factorial of?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文