cmath.不能用log()和rand()函数编译代码



当我编译以下代码片段时,我从编译器得到这个错误消息:

/tmp/ccT1yBa1.o: In function `main':
test.c:(.text.startup+0x34): undefined reference to `log'
collect2: error: ld returned 1 exit status

_

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
void main(){
srand(time(NULL));
double r1 = (rand() % 1000)/1000.0;
double r2 = log(r1);
printf("%lfn",r2);
}
编制

gcc -O2 test.c

怎么了?

您忘记了-lm与数学库的链接。

gcc -O2 test.c -lm

最新更新