1

Can anyone tell me why I get this error when I try to compile my program in gcc. I have included the math library. I have included -lm. Is there something wrong with my compiler?

$ gcc -lm -Wall *.c
main.c: In function ‘main’:
/tmp/ccqqxFDD.o: In function `main':
main.c:(.text+0x324): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Here it is.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{   
    int x1 = 5;
    int x2 = 7;
    int y1 = 11;
    int y2 = 8;    
    double distance = 0; 
    distance=sqrt((pow((x2- x1), 2))+(pow((y2 - y1), 2)));
    printf(" distance is: %lf \n", distance);
    return 0;
}
Gluttton
  • 5,739
  • 3
  • 31
  • 58
cokedude
  • 379
  • 1
  • 11
  • 21
  • 4
    I think you need to put the libraries after the source files :- gcc -Wall *.c -lm so that it knows what symbols to look for that are missing to resolve – jcoder Oct 13 '14 at 13:25
  • Try compiling a minimal program: `#include \n int main() { sqrt(3.0); return 0; }` and see if it reproduces the problem. – ilent2 Oct 13 '14 at 13:27
  • We really need to see some code/source, otherwise we are just guessing. – ilent2 Oct 13 '14 at 13:29
  • 2
    possible duplicate of [sqrt from math.h causes compile error](http://stackoverflow.com/questions/1711915/sqrt-from-math-h-causes-compile-error) – Mohit Jain Oct 13 '14 at 13:42

1 Answers1

3

Is there something wrong with my compiler?

No.

I have included -lm.

This is not enough, You also need respect order of options:

$ gcc -Wall *.c -lm

According to the man gсс

...
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant.
...
-llibrary
...
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.
...

Gluttton
  • 5,739
  • 3
  • 31
  • 58