43

Why does the following bit of code work in C:

int res = pow(2, 3);
printf("%d\n", res);

while this other doesn't?

int a = 2;
int b = 3;

int res = pow(a, b);
printf("%d\n", res);

Even if I try

double a = 2;
double b = 3;

double res = pow(a, b);
printf("%f\n", res);

I get an

undefined reference to `pow'

What am I doing wrong?

progyammer
  • 1,498
  • 3
  • 17
  • 29
devoured elysium
  • 101,373
  • 131
  • 340
  • 557

4 Answers4

66

When it works, it's because the calculation was done by the compiler itself (and included in the binary as if you wrote it out)

printf("8\n");

When it doesn't work, is because the pow function is included in the math library and the math library isn't linked with your binary by default.
To get the math library to be linked, if your compiler is gcc, use

gcc ... -lm ...

With other compilers, should be the same :)
but read the documentation

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 4
    You're spot on! GCC uses MPFR. Here's some info: http://gcc.gnu.org/gcc-4.3/changes.html#mpfropts – swatkat Nov 13 '10 at 18:46
  • MPFR! Woh! :) Totally knock me out when I was trying exactly the same thing and can't believe what I have seen. – Deqing Aug 26 '14 at 09:05
17

undefined reference to 'pow' sounds like a linker error. You are not linking in the math library, even if you introduce the function pow by including <math.h>.

With gcc, use the -lm command line parameter to link in the math lib.

eq-
  • 9,986
  • 36
  • 38
  • 11
    If you notice, the identical answers were posted <= 1 minute apart. That might help explain why. – Lucas Oct 03 '13 at 00:55
3

Use like this

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

int main(void)
{
  for(int i = 1; i < 5; i++)
     printf("pow(3.2, %d) = %lf\n", i, pow(3.2, i));  
  return 0;
}

Output:

pow(3.2, 1) = 3.200000

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Karthik Ratnam
  • 3,032
  • 2
  • 20
  • 25
-6

undefined reference to `pow'

because power to any number must have an integer value as power

pow(x,y)
where, x must be real and y must be a whole number
Javed Akram
  • 15,024
  • 26
  • 81
  • 118
  • 1
    I know this is old, but just to mention, this is not correct, pow() takes two double arguments. ;) – Pascal Apr 12 '12 at 16:18