Eclipse math.h linker error

As you already know the buggy nature of the eclipse ide, there is also a bug on its linker. Actually it is not a bug only in eclipse, because the error is depend on gcc and its inability to solve math library linking after or middle of the code compilation. Let’s explain this phenomenon with an example:

Asssume that we have the following example.c code:

#include <stdio.h>
#include <math.h>
int main(void)
        double x = 4.0;
        double result = sqrt(x);
        printf("The square root of %lf is %lf\n", x, result);
        return 0;

If we compile this code in bash terminal with:

$ gcc -lm test.c -o test

we have an error as undefined reference to `sqrt‘ (or any other function that called from math.h library) Interestingly if we have a static variable inside the sqrt like ‘sqrt(12.2)’ the compiler don’t give us any error. This happens because when we give the gcc  ‘-lm‘ option, we link the libm.a and to the compiler. “.a" files are static libraries, as opposed to “.so" files which are dynamic libraries. Normally gcc looks for dynamic libraries if available unless passed -static.  In ”sqrt(12.2)” case gcc is called ‘libm.a’ and not call the function sqrt in the run time, simply assign the value to the static variable.

In bash terminal. if we compile this code with:

$ gcc test.c -o test -lm

problem would be solved for bothe cases. to to this in Eclipse:

  1. Right click on your project in Project Explorer and select Properties.
  2. Go to C\C++ Build -> Settings -> Tool Settings -> Gcc Linker -> Libraries and click on green plus button to add a new library. When the dialog pops up, write m, and Eclipse will automatically add the –Im flag.


source Okumaya devam et