Why do you have to link the math library in C?

CCompilationmath.h

C Problem Overview


If I include <stdlib.h> or <stdio.h> in a C program I don't have to link these when compiling but I do have to link to <math.h>, using -lm with gcc, for example:

gcc test.c -o test -lm

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

C Solutions


Solution 1 - C

The functions in stdlib.h and stdio.h have implementations in libc.so (or libc.a for 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 libm.a for static linking), and libm is not linked in by default. There are historical reasons for this libm/libc split, none of them very convincing.

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

Solution 2 - C

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".

Solution 3 - C

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

Solution 4 - C

Because time() and some other functions are builtin defined in the C library (libc) itself and GCC always links to libc unless you use the -ffreestanding compile option. However math functions live in libm which is not implicitly linked by gcc.

Solution 5 - C

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?

Solution 6 - C

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.

Solution 7 - C

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.

Solution 8 - C

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.

Solution 9 - C

> 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.

Solution 10 - C

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.

Solution 11 - C

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.

Solution 12 - C

It's a bug. You shouldn't have to explicitly specify -lm any more. Perhaps if enough people complain about it, it will be fixed. (I don't seriously believe this, as the maintainers who are perpetuating the distinction are evidently very stubborn, but I can hope.)

Solution 13 - C

All libraries like stdio.h and stdlib.h have their implementation in libc.so or libc.a and get linked by the linker by default. The libraries for libc.so are automatically linked while compiling and is included in the executable file.
But math.h has its implementations in libm.so or libm.a which is seperate from libc.so and it does not get linked by default and you have to manually link it while compiling your program in gcc by using -lm flag.

The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.

Here read the item no 14.3, you could read it all if you wish: Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage: using the library

Solution 14 - C

Note that -lm may not always need to be specified even if you use some C math functions.

For example, the following simple program:

#include <stdio.h>
#include <math.h>

int main() {

    printf("output: %f\n", sqrt(2.0));
    return 0;
}

can be compiled and run successfully with the following command:

gcc test.c -o test

Tested on gcc 7.5.0 (on Ubuntu 16.04) and gcc 4.8.0 (on CentOS 7).

The post here gives some explanations:

> The math functions you call are implemented by compiler built-in functions

See also:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNopeView Question on Stackoverflow
Solution 1 - CephemientView Answer on Stackoverflow
Solution 2 - CNosrednaView Answer on Stackoverflow
Solution 3 - CR.. GitHub STOP HELPING ICEView Answer on Stackoverflow
Solution 4 - CismailView Answer on Stackoverflow
Solution 5 - CBastien LéonardView Answer on Stackoverflow
Solution 6 - CBill the LizardView Answer on Stackoverflow
Solution 7 - CardsrkView Answer on Stackoverflow
Solution 8 - CLou FrancoView Answer on Stackoverflow
Solution 9 - CAdrian PanasiukView Answer on Stackoverflow
Solution 10 - CSimonView Answer on Stackoverflow
Solution 11 - CEvan TeranView Answer on Stackoverflow
Solution 12 - CSteve SummitView Answer on Stackoverflow
Solution 13 - CSaptarshi dasView Answer on Stackoverflow
Solution 14 - CjdhaoView Answer on Stackoverflow