1

Why does this compile and run this w/o the "-lm" switch on gcc:

#include <stdio.h>
#include <math.h>

int main()
{
    printf("2 to the 8th power is %f\n",pow(2.0,8.0));
    return(0);
}

but this:

#include <stdio.h>
#include <math.h>

int main()
{
    float a,b;
    a = 2.0;
    b = 8.0;
    printf("2 to the 8th power is %f\n",pow(a,b));
    return(0);
}

gives the error:

undefined reference to `pow'

unless you link the math library with -lm

The behavior is the same if I use doubles rather than floats. Is there some sort of rudimentary pow() function hidden in standard library, or is the linker just resigned to working with idiots and links the math library for really simple cases?

I'm using gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 if that makes any difference. It's not a big deal, just curious why that happens, thanks!

1 Answers1

1

I had myself, a problem of understanding, what is wrong with the above. I got the same behaviour with gcc -O0. Running executable with strace and gdb showed that no function call made at all.

Scratched my head, read some comments and got it. Me alone, would have guessed the answer for hours. All credits goes to commenters

Try to change your code to

....
double t = (int)(2.0 + 1.0) % 2 + 1.0;
double r = pow(2.0+t,8.0);
....

With -O0 flag you should hopefully get undefined reference to 'pow' message.

user14063792468
  • 839
  • 12
  • 28