问题
I have a small bit of code:
#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;
}
I have linked -lm
in my Eclipse compiler settings: 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"
, so I'm not sure what the source of the error is. What am I not doing corectly?
回答1:
Put -lm
to the end of the command line.
回答2:
Your -lm
option doesn't work, because it needs to follow the input sources on the command line:
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.
The first pow(2.0,7.0)
works because it's evaluated by the compiler as a constant expression, and doesn't need pow
at runtime.
回答3:
You need to link to the math library with the -lm flag for the compiler.
The first example work because the compiler can inline the value(in fact, 2^7 will always be equal to 128), but when using variable parameter to pow(), it can't inline its value, since its value will only be know at runtime, thus you need to explicetely link the standard math library, where instead of inlining the value, it will call the function.
来源:https://stackoverflow.com/questions/16802263/cs-pow-doesnt-work-with-a-variable-exponent