The ISO C standard defines (in clause 4) two classes of conforming implementation. A
conforming hosted implementation supports the whole standard including all the library
facilities; a conforming freestanding implementation is only required to provide certain
library facilities: those in <float.h>, <limits.h>, <stdarg.h>, and <stddef.h>; since
AMD1, also those in <iso646.h>; since C99, also those in <stdbool.h> and <stdint.h>;
and since C11, also those in <stdalign.h> and <stdnoreturn.h>. In addition, complex
types, added in C99, are not required for freestanding implementations.The standard also defines two environments for programs, a freestanding environment,
required of all implementations and which may not have library facilities beyond those
required of freestanding implementations, where the handling of program startup and termination are implementation-defined; and a hosted environment, which is not required,
in which all the library facilities are provided and startup is through a function int main
(void) or int main (int, char *[]). An OS kernel is an example of a program running
in a freestanding environment; a program using the facilities of an operating system is an
example of a program running in a hosted environment.GCC aims towards being usable as a conforming freestanding implementation, or as the
compiler for a conforming hosted implementation. By default, it acts as the compiler for a
hosted implementation, defining STDC_HOSTED as 1 and presuming that when the names
of ISO C functions are used, they have the semantics defined in the standard. To make it act
as a conforming freestanding implementation for a freestanding environment, use the option
‘-ffreestanding’; it then defines STDC_HOSTED to 0 and does not make assumptions
about the meanings of function names from the standard library, with exceptions noted
below. To build an OS kernel, you may well still need to make your own arrangements for
linking and startup.摘自 GCC7.5.0
C标准定义了两种实现:hosted implementation和freestanding implementation。
freestanding implementation:不能包含c标准库,只能包含基本的头文件。
hosted implementation:能包含所有的c标准库。
freestanding environment:在这种环境下编译的程序,不能包含完整的c标准库,甚至连main入口都没有。所以freestanding environment应该是指裸机开发环境,例如,kernal开发,c标准库开发。
hosted environment:这种环境就是我们通常的编译环境,main作为入口,可以包含完整的c标准库。所以基于操作系统之上的应用程序开发,可谓之为hosted environment,这种环境下就可以直接使用现成的c标注库啦。
gcc作为编译器,既要支持freestanding implementation的程序编译又要支持hosted implementation的程序编译。怎么控制呢?__STDC_HOSTED__宏;当__STDC_HOSTED__的值为1时,表示hosted;当__STDC_HOSTED__的值为0时,表示freestanding;默认__STDC_HOSTED__的值为1。如果想使用gcc编译freestanding的程序,就需要使用‘-ffreestanding’编译选项。
freestanding 和 hosted的区别与联系
从应用的角度来看,hosted比freestanding更便于应用程序的开发。
从OS之下的底层开发来看,freestanding保留了足够的灵活性,可供底层开发人员任意驰骋。
gcc编译器这种把语言本身和库独立对待的方式,使之能够适应更广泛的开发环境。