Answer the question
In order to leave comments, you need to log in
What is the best programming style to write file inclusions?
There is a multi-file C project.
For example, it contains header.h and header.c files.
Do I need to write the following in the header.c file: #include "header.h"
?
Second question.
If the header.h file says: #include <stdio.h>
,
then is it necessary to write the same inclusion in the header.c file?
Answer the question
In order to leave comments, you need to log in
Let's figure it out.
.h files are needed to describe data types and functions that can be used from different .c files. If you have a self-contained .c file, it doesn't need a header file at all.
When you describe the function int make_me_coffie(int coffeine_level) in a C file, then in order to be able to call it from other C files, you need to inform these files about the existence of such a function. To do this, you can add a description of this function in each of these C files.
So for example in kitchen.c you can write
int make_me_coffie(int );
and then safely use this function. No inclusions are needed here at all. Everyone understands that dragging a bunch of definitions of types and functions into each C file is tritely inconvenient, and can lead to errors, so we came up with includes. An include includes the contents of a file where it is. That is, all those function definitions will appear in your file before it is built.
Now to your questions. It is not necessary to include header.h in the body of header.c (since there is nothing mandatory at all) - it is logical and reasonable. If you already have one header module, then most likely the functions and data types are described in header.h, which means header.c should include it.
Including in header.c if it is already included in header.h is absolutely not necessary, since our header.c already includes header.h which includes stdio.h - which means that all the necessary function definitions will already be in our file. However, you can include stdio.h, it will not hurt anything thanks to the define system that is usually added to each header file to prevent multiple inclusion of it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question