sqrt from math.h导致链接器错误“未定义对sqrt的引用”只有当参数不是常数时 [英] sqrt from math.h causes linker error "undefined reference to sqrt" only when the argument is not a constant

查看:246
本文介绍了sqrt from math.h导致链接器错误“未定义对sqrt的引用”只有当参数不是常数时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a small program, as follows:

  #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;
 }

当我尝试使用下面的命令编译时, 。

When I try to compile this with the following command, I get a compiler error.

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(10.2)这样的常量替换sqrt(xx)调用中的变量,那么它编译就好了。或者,如果我明确链接如下:

If I replace the variable in the call to sqrt(xx) with a constant like sqrt(10.2), it compiles just fine. Or, if I explicitly link like the following:

gcc -Wall -lm calc.c -o calc

它也很好。任何人都可以告诉我这是什么原因?我已经是一个C程序员很长一段时间了(我使用math.h编写了类似的小程序),我从来没有见过这样的。

It also works just fine. Can anyone tell me what's causing this? I've been a C programmer for a long time (and I've written similar small programs using math.h) and I have never seen anything like this.

我的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()实际上不是。

If you look at the output of the compiler in the case where you used sqrt(10.2), I'll bet you see that a call to sqrt() isn't actually made.

这是因为GCC识别了可以特殊处理的几个功能。这使它能够进行某些优化,在这种情况下常数折叠。此类特殊功能称为内置

This happens because GCC recognizes several functions that it can treat specially. This gives it the ability to do certain optimizations, in this case Constant folding. Such special functions are called Built-ins.

在必须链接到数学库的情况下(因为您使用变量调用它),您需要明确链接它。有些操作系统/编译器会为你做这些,这也是为什么你过去可能没有注意到的。

In the case where it must link to the math library (because you're calling it with a variable), you need to link it explicitly. Some operating systems/compilers do it for you, which is why you might not have noticed in the past.

这篇关于sqrt from math.h导致链接器错误“未定义对sqrt的引用”只有当参数不是常数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆