使用pow()函数会在C中引发未定义的引用错误 [英] Using pow() function throws undefined reference error in C

查看:923
本文介绍了使用pow()函数会在C中引发未定义的引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码在C语言中起作用:

Why does the following bit of code work in C:

int res = pow(2, 3);
printf("%d\n", res);

这其他人没有吗?

int a = 2;
int b = 3;

int res = pow(a, b);
printf("%d\n", res);

即使我尝试

double a = 2;
double b = 3;

double res = pow(a, b);
printf("%f\n", res);

我得到一个

对"pow"的未定义引用

undefined reference to `pow'

我在做什么错了?

推荐答案

它起作用时,是因为计算是由编译器本身完成的(并包括在二进制文件中,就像您写出来一样)

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");

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

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

这篇关于使用pow()函数会在C中引发未定义的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆