Using pow() function throws undefined reference error in C Using pow() function throws undefined reference error in C c c

Using pow() function throws undefined reference error in C


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


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.


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