0

I am using sin function in one of my c program.

The program runs prefectly on fedora machine but ginving reference issue in ubuntu machine

I have compile it using -lm like following:

gcc -lm kepler.c -o a.out --working on fedora, but not on ubuntu

gcc kepler.c -lm -o a.out --Working on both, fedora and ubuntu

    /tmp/ccshH33a.o: In function `kepler':
    /tmp/28/kepler.c:7: undefined reference to `sin'
    collect2: error: ld returned 1 exit status

So can any one explains about the position of -lm, and why its working on fedora machine for both cases?

Thanks in Adavance.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
  • Which versions of the according compilers do you have? The general rule is that the libraries should come after the object files where they are referenced. In your case, you don't have object files but source files, so I could imagine the same applies. – Ulrich Eckhardt Jul 29 '15 at 06:06
  • See [Why does the order in which libraries are linked sometimes cause errors in GCC?](http://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc) – Cornstalks Jul 29 '15 at 06:09
  • 1
    Put `-lm` to the very end of the `gcc` command – timrau Jul 29 '15 at 06:11
  • yes, sure. I have done that, but I want to know how its compiled succesfully on ferdora? – Akki Tyagi Jul 29 '15 at 06:16
  • thanks, I'm reading it. :) – Akki Tyagi Jul 29 '15 at 06:20

1 Answers1

1

gcc like all common compilers internally launches different programs : at least a compiler and a linker. -lm option is intended for linker, as is -o a.out. BTW,-o a.outis just a no-op sincea.outis the default name when-o` option is absent.

Why -lm before kernel.c may fail : as explained in the answer to the question referenced by Cornstalks in comment, linker processes its arguments left to right, so dependant libraries must come after modules calling them

Why could it succeed on fedora : object modules will always be included in the executable program, so it can makes sense to always put them first in the argument list passed to the linker, of for the linker to process them first

Why did it work on Fedora and not on Ubuntu : I assume it is not same version of gcc, and the one on Fedora is more tolerant.

Anyway, the correct way is to always put dependant libraries after the modules (or other libraries) calling them.

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252