为什么我得到“未定义的 sqrt 引用"?即使我包含 math.h 标头也会出错? [英] Why am I getting "undefined reference to sqrt" error even though I include math.h header?
本文介绍了为什么我得到“未定义的 sqrt 引用"?即使我包含 math.h 标头也会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 C 很陌生,我有这个代码:
I'm very new to C and I have this code:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0.5;
double result = sqrt(x);
printf("The square root of %lf is %lf
", x, result);
return 0;
}
但是当我编译这个时:
gcc test.c -o test
我收到这样的错误:
/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
为什么会这样?sqrt()
不在 math.h
头文件中吗?cosh
和其他三角函数出现同样的错误.为什么?
Why does this happen? Is sqrt()
not in the math.h
header file? I get the same error with cosh
and other trigonometric functions. Why?
推荐答案
生成可执行文件时必须链接数学库.如何做到这一点因环境而异,但在 Linux/Unix 中,只需在命令中添加 -lm
即可:
The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm
to the command:
gcc test.c -o test -lm
数学库名为 libm.so
,-l
命令选项假定有 lib
前缀和 .a
或 .so
后缀.
The math library is named libm.so
, and the -l
command option assumes a lib
prefix and .a
or .so
suffix.
这篇关于为什么我得到“未定义的 sqrt 引用"?即使我包含 math.h 标头也会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文