为什么abs()和fabs()在C中的两个不同的头文件中定义

San*_*ose 14 c header-files c-standard-library

标准库函数abs()声明中stdlib.h,而fabs()math.h.

为什么它们位于不同的标题中?

mya*_*aut 5

math.h首次出现在第7研究Unix中.很难说它是如何到达那里的.例如,[1]声称C库的某些部分是从包含troffC编译器的"PWB/Unix"合并而来的pcc,但我不能证明它.

另一个有趣的信息是来自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.
Run Code Online (Sandbox Code Playgroud)

<...>

(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>.
Run Code Online (Sandbox Code Playgroud)

如果你看一下V7命令makefile,只有少数C程序与-lmflag 链接.所以我的结论是推测性的:

  1. libm.a(和math.h)主要用于FORTRAN程序,因此它被分成库以减少二进制占用空间(请注意它是静态链接的).
  2. 没有多少机器具有浮点支持.例如,您需要购买 PDP-11的可选FPP [2],在Unix中还有libfpsim仿真库来缓解这种情况,因此在早期的C程序中很难使用浮点数.

1. Berkeley之前的UNIX历史:UNIX演变:1975-1984

2. PDP-11架构


Dav*_*Kok -1

大多数运算符(例如 + - / *)也是数学运算符,但它们也很容易获得。在编程时,您会使用大量数学知识,开发人员已经开始区分日常工作所需的数学知识和仅在某些时候使用的更专业的数学知识。Abs 是经常使用的功能之一。就像指针算术一样,您只想知道差异来计算内存块的大小。但你对知道哪个记忆力较高、哪个记忆力较低并不感兴趣。

总结一下:abs经常被使用,因为它计算两个整数的差。例如,两个指针之间的差异也是一个整数。stdlib.h 中也是如此。然而 fabs 并不是你需要的东西,除非你正在做数学特定的事情。因此它在 math.h 中。