如果我包含<stdlib.h>或<stdio.h>在C程序中,我不必在编译时链接这些,但我必须链接到<math.h>,使用-lmgcc,例如:
gcc test.c -o test -lm
Run Code Online (Sandbox Code Playgroud)
这是什么原因?为什么我必须显式链接数学库而不是其他库?
我正在尝试在C中制作一个简单的斐波那契计算器,但在编译时gcc告诉我,我错过了战俘和地板功能.怎么了?
码:
#include <stdio.h>
#include <math.h>
int fibo(int n);
int main() {
printf("Fib(4) = %d", fibo(4));
return 0;
}
int fibo(int n) {
double phi = 1.61803399;
return (int)(floor((float)(pow(phi, n) / sqrt(5)) + .5f));
}
Run Code Online (Sandbox Code Playgroud)
输出:
gab@testvm:~/work/c/fibo$ gcc fib.c -o fibo
/tmp/ccNSjm4q.o: In function `fibo':
fib.c:(.text+0x4a): undefined reference to `pow'
fib.c:(.text+0x68): undefined reference to `floor'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud) 我是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和其他三角函数有同样的错误.为什么?
我有以下代码(根据这个问题的基础知识):
#include<stdio.h>
#include<math.h>
double f1(double x)
{
double res = sin(x);
return 0;
}
/* The main function */
int main(void)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当gcc test.c我编译它时,我得到以下错误,我无法解决原因:
/tmp/ccOF5bis.o: In function `f1':
test2.c:(.text+0x13): undefined reference to `sin'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
但是,我编写了各种sin从main函数内部调用的测试程序,并且这些程序完美地工作.我必须在这里做一些明显错误的事 - 但它是什么?
我创建了一个小程序,如下所示:
#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) 我的程序的一部分是计算sqrt浮点数.当我写sqrt(1.0f);成功编译程序时,但是当我编写sqrt(-1.0f);
编译失败时undefined reference to 'sqrt'- 我想在这种情况下nan会返回值...我编译程序uing gcc.当我使用visual studio编译它时,它会成功地编译为sqrt的负参数.如何解决问题谢谢