【问题标题】:Why am I getting this error when trying to use log from math.h in C? [duplicate]为什么在 C 中尝试使用 math.h 中的日志时出现此错误? [复制]
【发布时间】:2013-08-04 09:53:02
【问题描述】:

我需要在程序中使用日志来完成作业。我在我的机器上运行了这个测试程序来查看日志功能是如何工作的(如果可以的话),我在构建过程中得到了以下错误。

代码

/* log example */
#include <stdio.h>      /* printf */
#include <math.h>       /* log */

int main()
{
  double param, result;
  param = 5.5;
  result = log (param);
  printf ("log(%f) = %f\n", param, result );
  return 0;
}

错误

gcc -Wall -o "test" "test.c" (in directory: /home/linux/Development/codetest)
/tmp/ccCDqX7x.o: In function `main':
test.c:(.text+0x1b): undefined reference to `log'
collect2: ld returned 1 exit status
Compilation failed.

链接

这是 C99 代码,取自 tutorial 站点。

【问题讨论】:

    标签: c logarithm math.h


    【解决方案1】:

    -lm 添加到您的编译命令以链接到数学库。

    gcc -Wall -o "test" "test.c" -lm
    

    【讨论】:

    • 我一直觉得 gcc 默认不只是拉入数学库有点奇怪。
    • 古老的传统,部分可以追溯到并非所有 CPU 都内置浮点运算的时候,因此您可能需要软件仿真等。 FWIW:在 Mac OS X(10.8.4,以及更早的版本)上),您不需要-lm 来链接示例代码。
    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多