The standard library function abs()
is declared in stdlib.h
, while fabs()
is in math.h
.
Why are they reside in different headers?
The standard library function abs()
is declared in stdlib.h
, while fabs()
is in math.h
.
Why are they reside in different headers?
math.h first appears in 7th Research Unix. It is hard to tell how it got there. For example, [1] claims that bits of C library were merged from "PWB/Unix" which included troff
and C compiler pcc
, but I cannot prove it.
Another interesting piece of information is library manual from V7 Unix: intro.3:
(3) These functions, together with those of section 2 and those marked (3S), constitute library libc, which is automatically loaded by the C compiler cc(1) and the Fortran compiler f77(1). The link editor ld(1) searches this library under the `-lc' option. Declarations for some of these functions may be obtained from include files indicated on the appropri- ate pages.
<...>
(3M) These functions constitute the math library, libm. They are automati- cally loaded as needed by the Fortran compiler f77(1). The link editor searches this library under the `-lm' option. Declarations for these functions may be obtained from the include file <math.h>.
If you look into V7 commands makefiles, only few C programs are linked with -lm
flag. So my conclusion is speculative:
libm.a
(and math.h
) was primarily needed for FORTRAN programs mostly, so it was separated into library to reduce binary footprint (note that it was linked statically).1. A History of UNIX before Berkeley: UNIX Evolution: 1975-1984
Most operators like + - / * are also math operators yet these are also readily available. When programming you use so much math, that developers have started to differentiate between math that is needed for everyday stuff and math that is more specialized that you only use some of the time. Abs is one of those functions that are just used to often. Like with pointer arithmetic when you just want to know the difference to calculate the size of a memory block. But you are not interested in knowing which is higher in memory and which is lower.
So to sum up: abs is used often because it calculates the difference of two integers. The difference between two pointers for instance is also an integer. And so it is in stdlib.h. fabs how ever is not something you will need much unless you are doing math specific stuff. Thus it is in math.h.