【问题标题】:Square Root Program in C not Compiling [duplicate]C中的平方根程序未编译[重复]
【发布时间】:2019-03-05 13:07:12
【问题描述】:

刚开始学C,在一个C教程网站上找到了这个示例程序,编译时报错。

这是程序,根据用户输入计算数字的平方根:

#include <stdio.h>
#include <math.h>

int main()
{
    double num, root;

    /* Input a number from user */
    printf("Enter any number to find square root: ");
    scanf("%lf", &num);

    /* Calculate square root of num */
    root = sqrt(num);

    /* Print the resultant value */
    printf("Square root of %.2lf = %.2lf", num, root);

    return 0;
}

我在 Ubuntu 中使用 gcc 编译它:

gcc -o square_root square_root.c

这是错误:

/tmp/cc9Z3NCn.o: In function `main':
square_root.c:(.text+0x4e): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

我做错了什么?可以看到导入了math模块,为什么会报错呢?

同样,我今天刚开始学习 C,我只是想弄清楚如何让程序运行。感谢您的耐心等待,因为它必须是显而易见的。

【问题讨论】:

  • 程序运行良好。我认为编译器存在一些问题。您可以尝试在 ideone 等在线 IDE 上编译您的程序。它会起作用的。

标签: c compiler-errors square-root


【解决方案1】:

sqrt 存在于数学库中,因此您需要告诉您的程序使用-lm 链接到它:

gcc -o square_root square_root.c -lm

【讨论】:

  • 您能否进一步解释-lm 标志的作用?例如,l 代表链接,m 代表数学吗?为什么在程序顶部导入时需要告诉它链接到数学库?
  • C 并没有真正意义上的“导入”概念。 #include 正在做的是查找数学的标头(您的程序需要知道存在一个名为sqrt 的函数),而链接用于查找sqrt 的实现(请参阅stackoverflow.com/questions/924485/…)。是的,-l 代表“链接”,而数学库是 libm.solib 前缀和 .so 后缀被省略了,所以你只以 -lm 结尾。
【解决方案2】:

你需要用 -lm 标志编译它

gcc -o square_root square_root.c -lm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2012-12-16
    • 2018-09-01
    相关资源
    最近更新 更多