C 的背后的基本原理是什么?而不是默认包含这些功能?
我见过的每个用 C 编写的程序都是 #include
的
,至少是间接见过。没有它你就不能真正做很多有用的事情。
为什么它的函数不只是“标准 C”的一部分?
为什么我必须在 malloc()
之前先 #include
?
Every program written in C that I've ever seen #include
s <stdlib.h>
, at least indirectly. You can't really do much useful without it.
Why aren't its functions just part of "standard C"?
Why should I have to #include <stdlib.h>
before malloc()
ing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C 是一种简约语言。没有内置函数。
C is a minimalistic language. There are no built-in functions.
C 语言从一开始就设计用于普通应用程序(在“托管环境”中运行)和操作系统内核(以及其他专用环境,在“独立环境”中运行)。在后者中,诸如
malloc()
之类的普通C库函数可能不可用。为了允许同一编译器用于托管环境和独立环境,库函数不会硬编码到编译器中,而是放入编译器加载的头文件中 - 例如
stdlib.h
。操作系统内核和其他专用程序不(也不能)包含这些标准标头。The C language was designed, from the start, to be used both in ordinary applications (running in a 'hosted environment') and OS kernels (and other specialized environments, running in a 'freestanding environment'). In the latter, ordinary C library functions like
malloc()
may be unavailable.In order to allow the same compiler to be used for both hosted and freestanding environments, library functions are not hardcoded into the compiler, but rather are placed into header files loaded by the compiler - such as
stdlib.h
. OS kernels and other specialized programs do not (and cannot) include these standard headers.并非所有程序都需要调用
malloc()
。那些确实需要动态内存分配的人可能更喜欢采用不同的方式。 C 并不试图强迫程序员采用单一的工作方式。Not all programs need to call
malloc()
. And those that do need dynamic memory allocation may prefer to do it a different way. C does not try to force a single way of working on programmers.这仍然是一个完全有效的程序,不需要 libc,并且除了与底层操作系统交互之外还可以做很多事情:
This is still a perfectly valid program that doesn't require libc and can do much stuff apart from interfacing with the underlying operating system:
我能想到的一个原因是,通过将 stdlib 函数放入库中,它们存在于自己的命名空间中,从而更容易重载它们。
考虑重载 malloc 可能听起来有点疯狂,但它是实现资源缓冲系统的一种方法,该系统可用于……在游戏循环期间动态创建游戏对象而不触发分配。您可以预先分配缓冲区,然后重载 malloc 以将对象创建到缓冲区中,而不是为它们分配新内存。
One reason I can think of is that by putting the stdlib functions into a library, they exist in their own namespace, making it easier to overload them.
It might sound a little crazy to think of overloading malloc, but it's one way to implement a resource buffering system that might be used for say... dynamically creating game objects during a game loop without triggering allocations. You can preallocate a buffer, then overload malloc to create the objects into the buffer rather than allocating new memory for them.