tags:

views:

1434

answers:

11

If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:

gcc test.c -o test -lm

What is the reason for that? Why do I have to explicitly link the math library but not the other libraries?

Any links explaining why would be appreciated. Thanks for the help :)

+1  A: 

stdio is part of the standard C library which, by default, gcc will link against.

The math function implementations are in a separate libm file that is not linked to by default so you have to specify it -lm. By the way, there is no relation between those header files and library files.

Simon
he knows that..he is asking *why*
Evan Teran
That does not explain "why"?
anon
He says why. Simon explains that some libraries are linked to by default, like stdio whereas the math library is not linked to by default so it has to be specified.
indyK1ng
I would say that the nature of the question is asking why libm is not linked by default (or even seperate from libc) since its contents are largely part of the c standard library.
Evan Teran
+1  A: 

I think it's kind of arbitrary. You have to draw a line somewhere (which libraries are default and which need to be specified).

It gives you the opportunity to replace it with a different one that has the same functions, but I don't think it's very common to do so.

EDIT: (from my own comments): I think gcc does this to maintain backwards compatibility with the original cc. My guess for why cc does this is because of build time -- cc was written for machines with far less power than we have now. A lot of programs have no floating-point math and they probably took every library that wasn't commonly used out of the default. I'm guessing that the build time of the UNIX OS and the tools that go along with it were the driving force.

Lou Franco
i think the mentality behind the question is that the contents of libm are largely part of the standard C library, why aren't they in libc?
Evan Teran
Lou Franco
+1  A: 

I would guess that it is a way to make apps which don't use it at all perform slightly better. Here's my thinking on this.

x86 OSes (and I imagine others) need to store FPU state on context switch. However, most OSes only bother to save/restore this state after the app attempts to use the FPU for the first time.

In addition to this, there is probably some basic code in the math library which will set the FPU to a sane base state when the library is loaded.

So, if you don't link in any math code at all, none of this will happen, therefore the OS doesn't have to save/restore any FPU state at all, making context switches slightly more efficient.

Just a guess though.

EDIT: in response to some of the comments, the same base premise still applies to non-FPU cases (the premise being that it was to make apps which didn't make use libm perform slightly better).

For example, if there is a soft-FPU which was likley in the early days of C. Then having libm separate could prevent a lot of large (and slow if it was used) code from unnecessarily being linked in.

In addition, if there is only static linking available, then a similar argument applies that it would keep executable sizes and compile times down.

Evan Teran
If you don't link with libm but touch the x87 FPU through other means (operations on floats, for example), the x86 kernel does need to save FPU state. I don't think this is a very good guess...
ephemient
of course if you manually use the FPU the kernel will still need to save/restore its state. I was saying that if you never use it (including not using libm) then it wont have to.
Evan Teran
Really it can very highly depend on the kernel. The math library the kernel uses could have a save_FPU_on_switch() function that turns it on, while others just detect if the FPU was touched.
Earlz
If I recall correctly, the whole issue long predates floating point coprocessors even being on microprocessors.
Nosredna
@earlz: the approach of having the math library request saving would be a terrible design. What if they use the FPU by some other means? The only sane approach (besides just always saving/restoring) would be to detect usage and then start saving/restoring.
Evan Teran
+1  A: 

There's a thorough discussion of linking to external libraries in An Introduction to GCC - Linking with external libraries. If a library is a member of the standard libraries (like stdio), then you don't need to specify to the compiler (really the linker) to link them.

EDIT: After reading some of the other answers and comments, I think the libc.a reference and the libm reference that it links to both have a lot to say about why the two are separate.

Note that many of the functions in 'libm.a' (the math library) are defined in 'math.h' but are not present in libc.a. Some are, which may get confusing, but the rule of thumb is this--the C library contains those functions that ANSI dictates must exist, so that you don't need the -lm if you only use ANSI functions. In contrast, `libm.a' contains more functions and supports additional functionality such as the matherr call-back and compliance to several alternative standards of behavior in case of FP errors. See section libm, for more details.

Bill the Lizard
Which doesn't answer the question of why you have to link in the match libraries separately. Obviously you want to have to link OpenGL libraries separately, but arguably the math libraries are generally useful.
David Thornley
@David: Right you are. It wasn't clear to me from the question that this was the bit that the OP was asking about. I was editing my answer as you commented.
Bill the Lizard
+15  A: 

The functions in stdlib.h and stdio.h have implementations in libc.so (or .a static linking), which is linked into your executable by default (as if -lc were specified). GCC can be instructed to avoid this automatic link with the -nostdlib or -nodefaultlibs options.

The math functions in math.h have implementations in libm.so (or .a for static linking), and libm is not linked in by default. There are hysterical raisins historical reasons for this libm/libc split, none of them very convincing.

Interestingly, the C++ runtime libstdc++ requres libm, so if you compile a C++ program with GCC (g++), you will automatically get libm linked in.

ephemient
OK, so this becomes a library design question - why are the libraries partitioned in this way?
anon
I bet to optimize the build time of UNIX itself (and the toolset that went along with it). At the time, it was probably the most complex thing that was being built in C.
Lou Franco
anything to do with fpu emulation? but for linux the eventual emulation is in kernel and not the libm.. right?
Joakim Elofsson
I've read that it's because it was common for Unix hackers to write their own math functions.
Bastien Léonard
This has nothing to do with Linux, since it was common long before Linux. I suspect it has something to do with trying to minimize executable size, since there's a lot of programs that don't need math functions.
David Thornley
On ancient systems, if math functions were contained in libc, then compiling all programs would be slower, the output executables would be larger, and runtime would require more memory, with no benefit to *most* programs which do not use these math functions at all. These days we have good support for shared libraries, and even when statically linking, the standard libraries are set up so that unused code can be discarded, so none of these are good reasons anymore.
ephemient
@ephemient: Do you have a link to get relevant information about this?
Eliseo Ocampos
@ephemient: that last comment is a good reason and likely to be true :-P. Edit that into your post and you've got my +1.
Evan Teran
@ephemient Even in the old days, linking to a library did not pull in all the contents of the library to the executable. Linkers, although an often ignored technology, have historically been quite efficent.
anon
@ephemient Also, shared libraries have been around for longer than you might think. They were invented in the 1950s, not the 1980s.
anon
It depends on how the objects in the library archive are set up, and since many of those systems predate **me**, I can't accurately make claims about them. It does make sense that the system's creators would do extra work up-front to split the library objects to enable this, though.
ephemient
Shared libraries have been around for forever, but as far as I know, many systems still used statically linked libraries even for libc. Stratus VOS, for example, is still deployed and maintained, and most deployments have no shared libraries at all...
ephemient
I suppose at the end of the day what we are looking at is nothing more than GCC conservatism: "it's always worked like that". I only wish they applied the same reasoning to their compiler extensions.
anon
I can't realistically imagine that anything would break if libm were merged into libc (and libm turned into an empty stub, so `-lm` doesn't fail). Oh well.
ephemient
@Niel Use -std=c99 or whatever.
Jed
+1  A: 

If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:

stdlib.h, stdio.h are the header files. You include them for your convenience. They only forecast what symbols will become available if you link in the proper library. The implementations are in the library files, that's where the functions really live.

Including math.h is only the first step to gaining access to all the math functions.

Also, you don't have to link against libm if you don't use it's functions, even if you do a #include <math.h> which is only an informational step for you, for the compiler about the symbols.

stdlib.h, stdio.h refer to functions available in libc, which happens to be always linked in so that the user doesn't have to do it himself.

Adrian Panasiuk
A: 

@Evan

If his code wasn't doing math-related stuff, he wouldn't need it (libm.so). Linkers don't lie. He's calling something that needs the math library. He supplied no source code, after all. FPU context? WTF?

I promise you, if all he was doing was printf("Hello, world\n"), he wouldn't need -lm.

xcramps
i agree that his code was obviously doing math stuff and did in fact require the -lm. I was making a guess as to why -lm is not simply part of -lc
Evan Teran
+9  A: 

Remember that C is an old language and that FPUs are a relatively recent phenomenon. I first saw C on 8-bit processors where it was a lot of work to do even 32-bit integer arithmetic. Many of these implementations didn't even have a floating point math library available!

Even on the first 68000 machines (Mac, Atari ST, Amiga), floating point coprocessors were often expensive add-ons.

To do all that floating point math, you needed a pretty sizable library. And the math was going to be slow. So you rarely used floats. You tried to do everything with integers or scaled integers. When you had to include math.h, you gritted your teeth. Often, you'd write your own approximations and lookup tables to avoid it.

Trade-offs existed for a long time. Sometimes there were competing math packages called "fastmath" or such. What's the best solution for math? Really accurate but slow stuff? Inaccurate but fast? Big tables for trig functions? It wasn't until coprocessors were guaranteed to be in the computer that most implementations became obvious. I imagine that there's some programmer out there somewhere right now, working on an embedded chip, trying to decide whether to bring in the math library to handle some math problem.

That's why math wasn't standard. Many or maybe most programs didn't use a single float. If FPUs had always been around and floats and doubles were always cheap to operate on, no doubt there would have been a "stdmath".

Nosredna
Heh, I am using Pade approximants for (1+x)^y in Java, in a desktop PC. Log, exp and pow are still slow.
quant_dev
Good point. And I've seen approximations for sin() in audio plugins.
Nosredna
+1  A: 

As ephemient said, the C library libc is linked by default and this library contains the implementations of stdlib.h, stdio.h and several other standard header files. Just to add to it, according to "An Introduction to GCC" the linker command for a basic "Hello World" program in C is as below:

ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o 
/usr/lib/crti.o /usr/libgcc-lib /i686/3.3.1/crtbegin.o
-L/usr/lib/gcc-lib/i686/3.3.1 hello.o -lgcc -lgcc_eh -lc 
-lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o /usr/lib/crtn.o

Notice the option -lc in the third line that links the C library.

ardsrk
+2  A: 

An explanation is given here:

So if your program is using math functions and including math.h, then you need to explicitly link the math library by passing the -lm flag. The reason for this particular separation is that mathematicians are very picky about the way their math is being computed and they may want to use their own implementation of the math functions instead of the standard implementation. If the math functions were lumped into libc.a it wouldn't be possible to do that.

[Edit]

I'm not sure I agree with this, though. If you have a library which provides, say, sqrt(), and you pass it before the standard library, a Unix linker will take your version, right?

Bastien Léonard
I don't think there's a guarantee that that'll happen; you might end up with a symbol conflict instead. It would probably depend on the linker and the layout of library. I still find that reason to be weak; if you're making a custom sqrt function, you really shouldn't give it the same name as the standard sqrt function, even if it does the same thing...
ephemient
Indeed, making your own function (non-static) named `sqrt` results in a program with undefined behavior.
R..
A: 

how we can make a calculator using functions i wnt to add sine,cosine,tan,log,antilog in my code hw i do it

sajal shah
uhh i dont know if this is the right place to ask that.
Casey