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?
Put
-lm
to the end of the command line.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.
Your
-lm
option doesn't work, because it needs to follow the input sources on the command line:The first
pow(2.0,7.0)
works because it's evaluated by the compiler as a constant expression, and doesn't needpow
at runtime.