Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pow() function throws undefined reference error in C

Tags:

c

math.h

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?

like image 238
devoured elysium Avatar asked Nov 13 '10 18:11

devoured elysium


People also ask

How do you fix undefined reference to POW in C?

a . You need to link your program with this library so that the calls to functions like pow() are resolved. This solved my issue.

Why POW function is not working in C?

The above error occurs because we have added “math. h” header file, but haven't linked the program to the following math library. Link the program with the above library, so that the call to function pow() is resolved.

What does the POW function do in C?

C pow() The pow() function computes the power of a number. The pow() function is defined in math.

Can we use POW in C?

pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function. then two numbers are passed. Example – pow(4 , 2); Then we will get the result as 4^2, which is 16.


1 Answers

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

like image 74
pmg Avatar answered Sep 26 '22 01:09

pmg