【问题标题】:main.c:(.text+0x324): undefined reference to `sqrt'main.c:(.text+0x324): 未定义对“sqrt”的引用
【发布时间】:2014-10-13 13:23:09
【问题描述】:

谁能告诉我为什么我在 gcc 中编译我的程序时会出现这个错误。我已经包含了数学库。我已包含-lm。我的编译器有问题吗?

$ gcc -lm -Wall *.c
main.c: In function ‘main’:
/tmp/ccqqxFDD.o: In function `main':
main.c:(.text+0x324): undefined reference to `sqrt'
collect2: ld returned 1 exit status

来了。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{   
    int x1 = 5;
    int x2 = 7;
    int y1 = 11;
    int y2 = 8;    
    double distance = 0; 
    distance=sqrt((pow((x2- x1), 2))+(pow((y2 - y1), 2)));
    printf(" distance is: %lf \n", distance);
    return 0;
}

【问题讨论】:

  • 我认为您需要将库放在源文件之后:- gcc -Wall *.c -lm 以便它知道要寻找哪些符号来解决问题
  • 尝试编译一个最小的程序:#include &lt;math.h&gt; \n int main() { sqrt(3.0); return 0; },看看它是否会重现问题。
  • 我们确实需要看一些代码/源代码,否则我们只是在猜测。

标签: c


【解决方案1】:

我的编译器有问题吗?

没有。

我已包含-lm

这还不够,你还需要尊重选项的顺序:

$ gcc -Wall *.c -lm

根据 man gсс

...
您可以混合使用选项和其他参数。在大多数情况下,您使用的顺序无关紧要。使用时顺序很重要 多个同类选项;例如,如果您指定 -L 更多 不止一次,目录按指定的顺序搜索。 此外,-l 选项的位置也很重要。
...
-图书馆
...
在命令中编写此选项会有所不同;这 链接器按顺序搜索和处理库和目标文件 它们是指定的。因此,foo.o -lz bar.o 在文件 foo.o 之后但在 bar.o 之前搜索库 z。如果 bar.o 引用 z 中的函数,则可能不会加载这些函数。
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 2015-02-13
    • 2020-05-20
    • 2011-07-12
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多