2

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
    may be the same question: http://stackoverflow.com/questions/10774177/pow-function-in-c, see the last answer – mitchelllc May 28 '13 at 22:10
  • possible duplicate of [Eclipse C/C++ (CDT) add -l option (linking math module) gcc -lm](http://stackoverflow.com/questions/8480013/eclipse-c-c-cdt-add-l-option-linking-math-module-gcc-lm) – Paul R May 28 '13 at 22:12
  • Works for me: http://ideone.com/vFQ0Nu – Mark Ransom May 28 '13 at 22:20

3 Answers3

8

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 library z after file foo.o but before bar.o. If bar.o refers to functions in z, 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.

ulidtko
  • 14,740
  • 10
  • 56
  • 88
7

Put -lm to the end of the command line.

nullptr
  • 11,008
  • 1
  • 23
  • 18
  • I'm not sure how to do that in Eclipse; the best I can do is `gcc -O0 -g3 -Wall -c -fmessage-length=0 -lm -MMD -MP -MF"src/PGM.d" -MT"src/PGM.d" -o "src/PGM.o" "../src/PGM.c"`, which doesn't fix the problem. –  May 28 '13 at 22:10
  • 2
    Does adding `m` in `Build -> Settings -> Linker -> Libraries` help? – nullptr May 28 '13 at 22:14
0

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.

user1115057
  • 1,815
  • 2
  • 18
  • 20