为什么我会收到"未定义的引用开方"错误即使我包括math.h中头? [英] Why am I getting "undefined reference to sqrt" error even though I include math.h header?

查看:221
本文介绍了为什么我会收到"未定义的引用开方"错误即使我包括math.h中头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C和我有这个code:

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\n", x, result);
  return 0;
}

但是,当我编译这个用:

But when I compile this with:

gcc test.c -o test

我得到这样一个错误:

I get an error like this:

/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 <​​/ code>命令选项假定 LIB preFIX和 .A 的.so 后缀。

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.

这篇关于为什么我会收到&QUOT;未定义的引用开方&QUOT;错误即使我包括math.h中头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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