Avinash Sonawane said:
Sir,
I am using gcc 4.6.1.
I have few questions regarding -lm switch. Please kindly guide me for the same.
1) Why I need to use -lm flag for math.h even if I had declared the
#include <math.h> in the code?
There are two distinct phases here: #include <math.h> tells the
compiler what the match functions look like, -lm actually links in the
code for them.
2) If it's all about linking the library then why I don't have to do
the same thing with stdio.h too?
Because that's *so* standard it's just assumed. More specifically,
there is a "standard C library" which is automatically linked with your
code, and all of the functions from <stdio.h> are in that library.
The better question would be why the C standard library function
prototypes aren't all automatically available, without a bunch of
#include's. To me it seems like they ought to be, but the people
writing the standards and the people writing the compilers don't agree
with me, so they aren't.
3) Or we have to add the -l'library' switch for every library
excluding stdio.h?
You've got a little bit of confusion going on here, which I've alluded
to above but I'll say more specifically here: a .h file is not a
library. A .h file contains function prototypes, which tell the
compiler how to generate code to make calls to the functions. That has
nothing at all to do with the code that's in the actual library --
that's what the -l flag pulls in.
OK, when I say it has "nothing to do with" that's overstating things a
bit: assuming no bugs, the .h file is designed to make sure calls to
the library are actually correct. But aside from that intention, they
are unrelated.
4) In case if the -l'library' switch is used for some specific
libraries only then please direct me to the complete list of such
libraries.
There is no complete list. Any particular system will have its own set
of libraries, depending on what's been installed on it. If you want,
you can create a library of your own that exists only on your own
system, and which won't be in any list.
If you're on a Unix-based system (including Linux and BSD), the man
page for a function will tell you both what .h file you need to #include
to compile it, and what library you need to use to link it. So, for
instance, the man page for the sin function says:
#include <math.h>
double sin(double x);
float sinf(float x);
long double sinl(long double x);
Link with -lm.
So, to be able to use sin(), sinf(), or sinl(), you need to
#include <math.h> and link with -lm