Home:ALL Converter>C header directive needed in function declaration file?

C header directive needed in function declaration file?

Ask Time:2015-09-09T23:27:34         Author:Adam Bak

Json Formatter

I am in the process of exploring the C programming language and have started to learn about header files.

I am working with three different files in my program. One header file and two source files:

encrypt.h

void encrypt(char *message);

encrypt.c

#include "encrypt.h"

void encrypt(char *message)
{    
    while(*message)
    {
        *message = *message ^ 31;
        message++;
    }   
}

main.c

#include <stdio.h>
#include "encrypt.h"

int main() 
{
    char myMessage[] = "Hello";

    printf("Regular message: %s\n", myMessage);
    encrypt(myMessage);
    printf("Encrypted message: %s\n", myMessage);        

    return 0;
}

The first line in the encrypt.c file is the #include statement:

#include "encrypt.h"

My question is why is this line necessary inside of this file. I was reading how the #include directive has a copy/paste functionality and inside of the main.c file I can see how this approach would support forward declaration for the encrypt function; however, inside of the encrypt.c file, it would seem that forward declaration of the function is not necessary, and was wondering what was the purpose of using the include directive in this situation?

I apologize if this question has been asked elsewhere and will mark as duplicate as required. Thank you for the clarification.

Author:Adam Bak,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32483621/c-header-directive-needed-in-function-declaration-file
John Bollinger :

In your particular case, it is not necessary for encrypt.c to include encrypt.h, but it is conventional for it to do so.\n\nThe normal purpose of header files is to provide a common location for declarations that can be shared among multiple source files. This avoids inconsistent declarations in different parts of the program, and when changes need to be made, it may reduce the number of files that need to be updated.\n\nencrypt.c does not need to include encrypt.h because the latter contains only a declaration of function encrypt(), and encrypt.c already has one in the form of a definition of that function. It is nevertheless useful, because it allows the compiler to verify that the declaration in encrypt.h is consistent with the definition in encrypt.c.\n\nIf encrypt.c defined more functions, and encrypt.h provided declarations for all of them, then it could also serve in encrypt.c to ensure that declarations of all functions therein were visible to all functions therein, thus overcoming any dependency on the relative order of the actual definitions.",
2015-09-09T15:40:43
yy