Search code examples
cfunctionheader-filesdefinition

Including the same header files in a self-defined function again, which are already included in the main programm?


Should I include the same header files, in the header file for that particular function or the function definition file, if I have included them already in the main program (the caller)?

For example:

/* Text of main programm */
#include <stdlib.h>                    /* Including the headers first */
#include <stdio.h>
#include <function.h>

int function(void);

int main (void)
{
     /* stdio.h is needed in main with f.e.
     printf("Let us using function!); */
     function();
     return(0);
}
_____________________________________________________________________

/* Headerfile for function ("function.h") */
/*
#include <stdlib.h>                Should I include the headers again here? 
#include <stdio.h> 
*/

int function (void);
_____________________________________________________________________

/* Definition of function ("function.c")*/

/*
#include <stdlib.h>                Should I include the headers again here? 
#include <stdio.h> 
*/

int function (void)
{
     printf("You know it right, baby!\n");
}

And what about if I want to use a special header and its function(s) in a self-defined function, but not need it in the main program?

I use C but want to use C++ in the future. If any difference between the answers for each of those is relevant for use, please mention it.

Thank you very much for your answers.


Solution

  • Proper practice is:

    • Each source file or header file should include header files that declare any identifier it is using.
    • Each source file should include “its own” header file, that is, the header file that declares every external identifier the source file defines.

    The reason for the former is to inform the compiler about the identifiers being used. This gives the compiler information it needs to compile the program correctly.

    The reason for the latter is to ensure that the declarations match the definitions. By including the header file in the source file, the compiler sees both the declaration and the definition during the same compilation, so it can produce an error message if the declaration is incompatible with the definition.

    It is possible to declare a function by putting its declaration explicitly in the source file where it is used instead of in a header, but this is bad practice because errors can arise due to typing mistakes or changes that are made in one file and not another.

    It is not necessary to include header files that declare identifiers not used by a source file, even if those identifiers are used by other files. In your example with function.c, function.c does not need to include <stdio.h> if it is not using any identifier from <stdio.h>. The fact that main.c does use <stdio.h> is irrelevant, because, when the compiler is compiling function.c, that is separate from main.c.