相关疑难解决方法(0)

为什么即使我包含math.h标题,我也会收到"对sqrt的未定义引用"错误?

我是C的新手,我有这个代码:

#include <stdio.h>
#include <math.h>
int main(void)
{
  double x = 0.5;
  double result = sqrt(x);
  printf("The square root of %lf is %lf\n", x, result);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译它时:

gcc test.c -o test
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误:

/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

为什么会这样?是sqrt()不是在math.h头文件中?我cosh和其他三角函数有同样的错误.为什么?

c linker linker-errors libm

98
推荐指数
5
解决办法
19万
查看次数

gcc:为什么链接数学库需要-lm标志?

我刚刚发现-lmgcc需要这个标志,以便编译一个从数学库中引用函数的程序.我想知道为什么在编译包含其他库(如时间库)的程序时不需要显式链接标志.如果我编写一个time()调用该函数的程序,即使没有链接选项也可以编译没有任何问题.但是如果没有-lm旗帜,那么涉及数学库的程序将无法运行.

任何人都可以解释这种行为背后的原因吗?谢谢你的时间.

gcc libc

62
推荐指数
0
解决办法
4万
查看次数

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

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

  #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;
 }
Run Code Online (Sandbox Code Playgroud)

当我尝试使用以下命令编译它时,我收到编译器错误.

gcc -Wall calc.c -o calc
Run Code Online (Sandbox Code Playgroud)

收益:

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

如果我用sqrt(10.2)之类的常量替换对sqrt(xx)的调用中的变量,它编译得很好.或者,如果我明确链接如下:

gcc -Wall -lm calc.c -o …
Run Code Online (Sandbox Code Playgroud)

c compiler-errors compilation

6
推荐指数
1
解决办法
8557
查看次数

标签 统计

c ×2

compilation ×1

compiler-errors ×1

gcc ×1

libc ×1

libm ×1

linker ×1

linker-errors ×1