Using pow() function throws undefined reference error in C

devoured elysium picture devoured elysium · Nov 13, 2010 · Viewed 57.8k times · Source

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?

Answer

pmg picture pmg · Nov 13, 2010

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