Trey
Trey

Reputation: 554

C - Header files

C requires different headers files, like stdio.h, stdlib.h, fcntl.h, etc.,for different functions and structure definitions, why is that? Underneath the hood it all boils down to libc so why not create a single header file with all the definitions and prototypes?

Upvotes: 2

Views: 386

Answers (3)

Peter
Peter

Reputation: 36597

Such things are not required by C.

It is possible, if you wish, to manually copy the contents of any header file into every source file, and do without the header file. However, that is error prone - if one of the source files changes, it is often necessary to update ALL the source files, and that makes it easy for typos to creep in. (If you copy the content of standard headers to all your compilation units, your code may also fail if built with a different compiler/library, since the content of the headers varies between implementations).

Including header files is simply a technique which allows the content of the header file to be (effectively) copied and pasted into every source file that includes it - and all source files get the SAME content (unless some other preprocessor macros cause things to happen conditionally). For standard headers (particularly those which provide functionality that can only be implemented in different ways on different systems) that aids portability.

Upvotes: 1

jxh
jxh

Reputation: 70382

The separate header files are defined the way they are largely due to historical compatibility. The C language was already being used on a variety of platforms before it was standardized.

The rationale behind the separate header files was likely a way to mimic modularity within the C language. Separate header files defined functionality provided by a module. This is not too different from how other languages provide functionality.

C also has a philosophy of minimalism, and so requiring every translation unit to compile the prototype declarations of all available functions regardless of whether they were going to be used would seem excessive.

Upvotes: 2

mnistic
mnistic

Reputation: 11010

These files are provided by the C standard library to make accomplishing common tasks easier. As to why the declarations and definitions are kept in separate files, it's for convenience and maintainability reasons. The same reason why, for example, the Linux kernel is not defined in a single C file, even though theoretically it could be.

Upvotes: 2

Related Questions