How to evaluate functions in GDB?

前端 未结 5 809
北海茫月
北海茫月 2020-12-03 01:18

I wonder why evaluate function doesn\'t work in gdb? In my source file I include, when debugging in gdb, these examples are wrong evaluations.

(gdb) p pow(3,         


        
相关标签:
5条回答
  • 2020-12-03 01:30

    The syntax for calling a function in gdb is

    call pow(3,2)
    

    Type

    help call
    

    at the gdb prompt for more information.

    0 讨论(0)
  • 2020-12-03 01:33

    My guess is that the compiler and linker does some magic with those particular functions. Most likely to increase performance.

    If you absolutely need pow() to be available in gdb then you can create your own wrapper function:

    double mypow(double a, double b)
    {
        return pow(a,b);
    }
    

    Maybe also wrap it into a #ifdef DEBUG or something to not clutter the final binary.

    BTW, you will notice that other library functions can be called (and their return value printed), for instance:

    (gdb) print printf("hello world")
    $4 = 11
    
    0 讨论(0)
  • 2020-12-03 01:40

    You need to tell gdb that it will find the return value in the floating point registers, not the normal ones, in addition to give the parameters the right types.

    I.e.:

    (gdb) p ((double(*)())pow)(2.,2.)

    $1 = 4

    0 讨论(0)
  • NAME
       pow, powf, powl - power functions
    
    SYNOPSIS
       #include <math.h>
    
       double pow(double x, double y);
    

    You shouldn't pass an int in the place of a double

     call pow( 3. , 2. )
    

    Also, passing a single argument is not enough, you need two arguments just like the function expects

     wrong: call pow ( 3. )
    
    0 讨论(0)
  • 2020-12-03 01:45

    Actually, at least on my LINUX implementation of gcc, many of the math functions are replaced with variants specific to the types of their arguments via some fancy substitutions pulled in by math.h and bits/mathcalls.h (included from within math.h). As a consequence, functions like pow and exp are called instead as __pow or *__GI___exp (your results may vary depending on the types of the arguments and perhaps the particular version).

    To identify what exactly the function is that is linked in to my code I put a break at a line where just that function is called, e.g. have a line in my code with b=exp(c);. Then I run in gdb up till that break point and then use the "step" command to enter the call from that line. Then I can use the "where" command to identify the name of the called routine. In my case that was *__GI___exp.

    There are probably cleverer ways to get this information, however, I was not able to find the right name just by running the preprocessor alone (the -E option) or by looking at the assembly code generated (-s).

    0 讨论(0)
提交回复
热议问题