简体   繁体   English

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

[英]Doubt regarding a tail optimized code under 'gdb'

Consider a tail recursive factorial implementation in C: 考虑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'. 我在'factorial'中放置一个断点,然后在'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. 假设它的尾部调用已经优化(我使用gcc -O2编译它),它应该至少击中断点,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? 我哪里错了?

Works fine for me. 对我来说很好。 You are membering to use the -g flag to add debug info when you compile? 您是成员在编译时使用-g标志添加调试信息? And you are remembering that you have to enter a number to calculate the factorial of? 你记得你必须输入一个数字来计算阶乘?

It could be that the factorial function is inlined into main. 可能是因子函数被内联到main中。 If this happens, there will be a second copy of factorial used for calls from other .c files; 如果发生这种情况,将会有第二个factorial副本用于来自其他.c文件的调用; that's where your breakpoint was. 这就是你的断点所在。 Try passing -fno-inline. 尝试传递-fno-inline。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM