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

查看:28
本文介绍了来自 math.h 的 sqrt 导致链接器错误“对 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
", 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 版本如下:

My version of gcc follows:

$ 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.

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

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