Possible Duplicate:
gcc: why the -lm flag is needed to link the math library?
Generally speaking, in order to use any of the math functions apart from including the header file math.h
you have to link with the linker option -lm. -l
here would mean the linker option to search of the specific library libm.o
.
My Question is
Why GCC does not include this library by default? Is it because the library heavily uses math-coprocessor and it requires to add the extra bit of code to initialize the floating point initialization (I may use the wrong terminology here)?
Note
I just reviewed all the answers mentioned in the link http://stackoverflow.com. This doesn't makes much sense to me. There are three basic reasons attributed
Here is the example
abhibhat@abhibhat-VirtualBox:~/Projects/GIPL6_2$ ls -1 Test_*|xargs -I{} sh -c "echo {} && echo "-----------------" && cat {}"
Test_withlibm.c
-----------------
#include<stdio.h>
#include<math.h>
int main() {
int i=20;
double output1=pow(2.618033988749895,i);
return 0;
}
Test_withoutlibm.c
-----------------
#include<stdio.h>
#include<math.h>
double Pow(double _X, int _Y) {
double _Z = 1;
for (; _Y; _X *= _X) {
if (_Y & 1) _Z *= _X;
_Y >>= 1;
}
return _Z;
}
int main() {
int i=20;
double output1=Pow(2.618033988749895,i);
return 0;
}
abhibhat@abhibhat-VirtualBox:~/Projects/GIPL6_2$ gcc Test_withlibm.c -lm -o Main_withlibm.o
abhibhat@abhibhat-VirtualBox:~/Projects/GIPL6_2$ gcc Test_withoutlibm.c -o Main_withoutlibm.o
abhibhat@abhibhat-VirtualBox:~/Projects/GIPL6_2$ objdump -d Main_withoutlibm.o|wc -l
261
abhibhat@abhibhat-VirtualBox:~/Projects/GIPL6_2$ objdump -d Main_withlibm.o|wc -l
241
It is to accomodate systems (mainly embedded) where floating point math is not possible or necessary. It's kind of historical indeed but don't forget that gcc
and most other C compilers were written in a time where a 386SX was considered a high performance processor.
To give an example, when I still worked in embedded computing, we used standard compilers (Microsoft and Borland) to generate code for our processors (Z80, 80186 and 68030). If the compilers had by default linked to the math library we would have been in trouble as none of our systems had floating point capabilities or even needed them.
It's true that 30 years afterwards it seems silly but the reason was sound at that time.
There are many libraries you may want, and libm
is just one of them.
For each of these, you may ask why it isn't included by default.
Perhaps libm
is more useful than others, but still, C prefers to keep things simple - you want a library, use -l
to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With