Search code examples
cmathcastingansi-c

ANSI-C pow function and type casting


This simple program below does not build for some reason. It says "undefined reference to pow" but the math module is included and I'm building it with -lm flag. It builds if I use the pow like pow(2.0, 4.0), so I suspect there is something wrong with my type casting.

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
   int i;

   for (i = 0; i < 10; i++) {
      printf("2 to the power of %d = %f\n", i, pow(2.0, (double)i));
   }

    return EXIT_SUCCESS;
}

Here is the bulid log:

**** Build of configuration Debug for project hello ****
make all 
Building file: ../src/hello.c
Invoking: GCC C Compiler
gcc -O0 -g -pedantic -Wall -c -lm -ansi -MMD -MP -MF"src/hello.d" -MT"src/hello.d" -o "src/hello.o" "../src/hello.c"
Finished building: ../src/hello.c

Building target: hello
Invoking: GCC C Linker
gcc  -o "hello"  ./src/hello.o   
./src/hello.o: In function `main':
/home/my/workspace/hello/Debug/../src/hello.c:19: undefined reference to `pow'
collect2: ld returned 1 exit status
make: *** [hello] Error 1

**** Build Finished ****

Solution

  • You've told it to use the math library in the wrong place -- you're specifying the math library when you compile (where it won't help) but leaving it out when you link (where it's actually needed). You need to specify it when you link:

    gcc -o "hello" ./src/hello.o -lm