Using pow() function throws undefined reference error in C

泪湿孤枕 提交于 2020-01-18 06:14:04

问题


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?


回答1:


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




回答2:


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.




回答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




回答4:


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


来源:https://stackoverflow.com/questions/4174080/using-pow-function-throws-undefined-reference-error-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!