【问题标题】:Why am I getting “undefined reference to sqrt” error even though I include math.h header? is there a permanent solution other than adding -lm?为什么即使我包含 math.h 标头,我也会收到“未定义的 sqrt 引用”错误?除了添加-lm之外,还有其他永久解决方案吗?
【发布时间】:2021-02-10 13:18:15
【问题描述】:
#include <stdio.h>
#include <math.h>
int main()
{
int x, y, x1, x2, y1, y2;
float distance;
//take the 1st points coordinates x axis and y axis
printf("Enter the coordinates of 1st point: ");
scanf("%d %d", &x1, &y1);

//take the 2st points coordinates x axis and y axis
printf("Enter the coordinates of 2nd point: ");
scanf("%d %d", &x2, &y2);

x = x2 - x1;
y = y2 - y1;

distance = sqrt((x * x) + (y * y));

//display result
printf("Distance = %.2f", distance);

return 0;

}

当我编译程序时,终端窗口中会显示一条错误消息。

/usr/bin/ld: /tmp/cc8GnBrR.o: 在函数'main'中: distance2.c:(.text+0xa4): undefined reference to 'sqrt' collect2:错误:ld 返回 1 个退出状态

这个问题除了“gcc filename.c -o filename -lm”有没有永久的解决方案

【问题讨论】:

  • 引用 man7.org/linux/man-pages/man3/sqrt.3.html - “与 -lm 链接。”这是使用该功能的官方方式。
  • 是的,还有其他永久性的​​“解决方案”。它们甚至不值得讨论,因为它们非常复杂。链接命令行上还有 4 次击键。正确的解决方案是接受您需要链接到-lm,句号。
  • 您需要了解声明定义之间的区别。 declaration 告诉编译器某物存在于somewhere,但不在这里。 定义 是某事物的实际实现。在sqrt 的情况下,标准&lt;math.h&gt; 标头声明 函数,但定义m 库中,您需要使用-l 选项。
  • 除了“gcc filename.c -o filename -lm”之外,有没有永久的解决方案你将有一个真正有趣的时间编写代码来连接如果您不想在库中链接,则连接到使用 SSL 保护其连接的数据库...
  • 如果在命令行中再添加 4 个字符是个问题,那么开发应用程序可能不是理想的任务。

标签: c ubuntu gcc compiler-errors


【解决方案1】:

sqrtlibm(数学库)中定义。除非您与 -lm 链接,否则您将得到一个未定义的符号。替代方案包括定义您自己的 sqrt 函数(不要那样做)。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2019-05-02
    • 2022-06-10
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2022-06-12
    相关资源
    最近更新 更多