我有一小段代码:
#include <math.h>
int main(void){
pow(2.0,7.0);
//Works
double x = 3.0;
pow(2.0,x);
//Fails with error "undefined reference to 'pow'"
return 0;
}
我在我的 Eclipse 编译器设置中链接了 -lm
:gcc -O0 -g3 -Wall -lm -c -fmessage-length=0 -MMD -MP -MF"src/pgm.d"-MT"src/pgm.d"-o "src/pgm.o""../src/pgm.c"
,所以我不确定错误的来源是什么.我做错了什么?
最佳答案
您的-lm
选项不起作用,因为it needs to follow命令行上的输入源:
It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus,
foo.o -lz bar.o
searches libraryz
after filefoo.o
but beforebar.o
. Ifbar.o
refers to functions inz
, those functions may not be loaded.
第一个 pow(2.0,7.0)
之所以有效,是因为它被编译器计算为常量表达式,并且在运行时不需要 pow
。
关于C 的 pow() 不适用于可变指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802263/