Using #include preprocessor directive

The #include preprocessor directive tells the compiler to include the code inside given file before compiling rest of the program. So, we can tell that this #include preprocessor includes the code of given file to the current file in which we are working.

For easily understand the function of #include preprocessor let’s take an example. Suppose we have a file named myfile.h in the same directory in which we are working now. And inside the file we have written the following code.

myfile.h

int sum(int a, int b){
  int total = a + b;
  return total;
}

Now, if our current file with .c extension in which we are working contains the following code.

#include <stdio.h>
#include "myfile.h"
int main(){
  int x, y, result;
  x = 20;
  y = 30;

  result = sum(x, y);
  printf("%d\n", result);
return 0;
}

Then the compiler will include the code inside myfile.h before the main program and the file will be as like as following.

#include <stdio.h>

int sum(int a, int b){   // code from myfile.h
  int total = a + b;
  return total;
}

int main(){    // main program
    int x, y, result;
    x = 20;
    y = 30;

    result = sum(x, y);
    printf("%d\n", result);
return 0;
}

Although we can write any code inside our created header file but it is not recommended as this practice is very confusing as well as error prone.

A header file can contains any portion of our C program although they are typically contain variable and function declarations as well as macro definitions in our program.

Method of using #include preprocessor directive in C

We can use #include preprocessor directive in two ways as like as following;

// two way of using #include preprocessor directive

#include <file_name>

#include "file_name"

#inculude  : It tells the compiler to include the file from where the system header files are located.

#inculude “file_name” : It tells the compiler to include the file from the current directory in where we are working now.