I have two files foo.c and bar.c that I compile separately with gcc -c
and then link. Both files need the stdio.h and stdlib.h headers.
Do I have to include them in both? Doesn't feel a little redundant? Should I maybe use #ifdef?
What's the best practice?
Each C file is a different translation unit. In other words, it is an entire separate program, syntactically complete and correct. Thus, each C file must compile independently of any other C file, and must contain every declaration for every identifier it uses, regardless of whether these declarations also appear in other C files. From the compiler point of view, each C file is a complete program by itself (albeit with unresolved references).
Header files are, by convention, files that contains declarations that must appear in a group of C files. Header files can be included by the preprocessor -- which is a simple textual copy-and-paste at the include point -- as a convenience to avoid manually duplicating declarations between the translation units.
Summing up: it is not redundant to include the same files in different C files -- it is formally required.
(Afterwards, you link object files, which are just smaller programs, into a larger final program. The larger program is roughly a summation of smaller subprograms, with all references resolved between them. Generally speaking, the linking phase does not know anything about the language structure of the original files that generated the resulting object file.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With