繁体   English   中英

仅当参数不是常量时,来自math.h的sqrt才会导致链接器错误“对sqrt的未定义引用”

[英]sqrt from math.h causes linker error “undefined reference to sqrt” only when the argument is not a constant

我创建了一个小程序,如下所示:

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

  int main(int argc, char *argv[]) {
    int i; 
    double tmp;
    double xx;

    for(i = 1; i <= 30; i++) {
      xx = (double) i + 0.01;

      tmp = sqrt(xx);
      printf("the square root of %0.4f is %0.4f\n", xx,tmp);
      sleep(1);
      xx = 0;
    }

    return 0;
 }

当我尝试使用以下命令对此进行编译时,出现编译器错误。

gcc -Wall calc.c -o calc

返回:

/tmp/ccavWTUB.o: In function `main':
calc.c:(.text+0x4f): undefined reference to `sqrt'
collect2: ld returned 1 exit status

如果我将sqrt(xx)调用中的变量替换为sqrt(10.2)之类的常量,则编译就可以了。 或者,如果我明确链接如下:

gcc -Wall -lm calc.c -o calc

它也可以正常工作。 谁能告诉我是什么原因造成的? 我很长时间以来一直是C程序员(并且我已经使用math.h编写了类似的小程序),但从未见过这样的事情。

我的gcc版本如下:

$ gcc --version
gcc (Ubuntu 4.3.3-5ubuntu4) 4.3.3
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$

如果您在使用sqrt(10.2)的情况下查看编译器的输出,我敢打赌,您会发现实际上并未调用sqrt()

发生这种情况是因为GCC可以识别几种可以特殊处理的功能。 这样,它就可以进行某些优化,在本例中为“ 常量折叠” 这样的特殊功能称为内置功能。

如果必须将其链接到数学库(因为要使用变量对其进行调用),则需要显式链接。 一些操作系统/编译器会为您执行此操作,这就是为什么您过去可能没有注意到的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM