Possible Duplicate:
Why do you have to link the math library in C?
When I write a program that uses functions from the math.h
library, why is it that I have to explicitly link to libm
even though they are part of the C standard library?
For instance, when I want to use the sin()
function I need to #include <math.h>
but I also need to pass -lm
to GCC. But for any other library from the standard library, I don't have to do that. Why the difference?
Link your program with the `libm. a' library, e.g. by specifying `-lm' on the link command line.
LIBM is the standard C library of basic mathematical functions, such as sin(x), cos(x), exp(x), etc. To include the LIBM functions, just add -lm on your link command line. The Intel compiler includes an optimized math library that contains optimized implementations of LIBM functions.
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 .
To compile C program with math. h library, you have to put -lm just after the compile command gcc number. c -o number, this command will tell to the compiler to execute program with math. h library.
In the old days, linkers were slow and separating the mostly unused math code from the rest made the compilation process go faster. The difference is not so great today, so you can add the -lm
option to your default compiler configuration.
Note that the header <math.h>
(or any other header) does not contain code. It contains information about the code, specifically how to call functions. The code itself is in a library. I mean, your program does not use the "<math.h>
library", it uses the math library and uses the prototypes declared in the <math.h>
header.
It's the same reason you have to explicitly link to libpthread
on most implementations. When something new and scary is added to the standard library, it usually first gets implemented as a separate add-on library that overrides some of the symbols in the old standard library implementation with versions that conform to the new requirements, while also adding lots of new interfaces. I wouldn't be surprised if some historical implementations had separate versions of printf
in libm
for floating point printing, with a "light" version in the main libc
lacking floating point. This kind of implementation is actually mentioned and encouraged for tiny systems in the ISO C rationale document, if I remember correctly.
Of course in the long-term, separating the standard library out like this leads to a lot more problems than benefits. The worst part is probably the increased load time and memory usage for dynamic-linked programs.
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