C语言 使用 pow() 函数在 C 中引发未定义的引用错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4174080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:02:12  来源:igfitidea点击:

Using pow() function throws undefined reference error in C

cmath.h

提问by devoured elysium

Why does the following bit of code work in C:

为什么以下代码在 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'

对‘pow’的未定义引用

What am I doing wrong?

我究竟做错了什么?

回答by pmg

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 powfunction 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

当它不起作用时,是因为该pow函数包含在数学库中,并且默认情况下数学库未与您的二进制文件链接。
要链接数学库,如果您的编译器是 gcc,请使用

gcc ... -lm ...

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

与其他编译器,应该是一样的:)
但阅读文档

回答by eq-

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

undefined reference to 'pow'听起来像是链接器错误。您没有在数学库中进行链接,即使您pow通过包含<math.h>.

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

使用 gcc,使用-lm命令行参数链接数学库。

回答by Karthik Ratnam

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

战俘(3.2,1)= 3.200000

回答by Javed Akram

undefined reference to `pow'

对‘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