Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-lm doesnt work unless it's at the end of the command [duplicate]

Tags:

c

gcc

math.h

Im currently writing a program for a uni asssessment and they have a set line to compile it, so if it doesn't work with that it won't be accepted. They command they use is

gcc -Wall -ansi -lm program.c -o program.out

My program will not compile that way, and it'll give me a undefined referance error (Referring to my log10 using math.h library) if i use:

gcc -Wall -ansi program.c -o program.out -lm

it works

What could be my issue?

Im using windows 10 64bit and have windows bash installed and gcc.

like image 717
Paloking Avatar asked Nov 18 '25 12:11

Paloking


1 Answers

This would be explained if your instructors are using gold and you are using GNU ld. These are two linkers, both are part of the GNU project, and both are commonly used with GCC.

If you are using GNU ld, you get the "traditional" behavior:

The order of specifying the -L and -l options, and the order of specifying -l options with respect to pathname operands is significant.

This means that you have to put -lm after any object files and libraries that depend on it.

However, if you are using gold, the -l options may appear first.

If you have gold installed on your system, you can test it yourself.

Here is what I get:

$ gcc -lm program.c 
/tmp/ccJmBjmd.o: In function `main':
program.c:(.text+0x15): undefined reference to `sin'
collect2: error: ld returned 1 exit status

But if I use gold, it works fine:

$ gcc -lm program.c -fuse-ld=gold
like image 58
Dietrich Epp Avatar answered Nov 21 '25 03:11

Dietrich Epp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!