C program to create your own header file/ Create your your own header file in C

In this program, we will create our own source (.c) and header file (.h) files and access their function. We will declare associate functions in header file and write code (definition) in source files.

Create your own Header and Source File Example in C

There will be three files

  • myfun.c - Source file that will contain function definitions.
  • myfun.h - Header file that will contain function declaration which have definition in myfun.c source file.
  • main.c – Main Source file that will contain complete code and access the functions which are declared in myfun.h header file.

Note: All three files should be in same directory.

Program: This program will read two integer numbers and calculate their sum, average. There will be two functions sumOfNumbers and avgOfNumbers which will be define and declare in myfun.c and myfun.h.

myfun.h - Header file

define macro MY_FUN, this will reduce multiple calling
of the header file

#ifndef MY_FUN
#define MY_FUN

/*function declarations*/
int sumOfNumbers(int x, int y);
float avgOfNumbers(int x, int y);


myfun.c - Source file

function name: sumOfNumbers()
this function will return sum of two numbers

int sumOfNumbers(int x, int y)
    int sum;
    sum = x + y;
    return sum;

function name: sumOfNumbers()
this function will return average of two numbers

float avgOfNumbers(int x, int y)
    int sum;
    float avg;

    sum = x + y;
    avg = sum / 2;
    return avg;

main.c - Main Source file

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

int main()
    int a, b;
    int sum;
    float avg;

    printf("Enter first number: ");
    scanf("%d", &a);
    printf("Enter second number: ");
    scanf("%d", &b);

    /*calling sumOfNumbers()*/
    sum = sumOfNumbers(a, b);

    /*calling avgOfNumbers()*/
    avg = avgOfNumbers(a, b);

    printf("Sum: %d \nAverage: %f\n", sum, avg);

    return 0;

Compiling the program

In turboc Compiler: - Just like normal program compilation, press ALT+F9 to compile and CTRL+F9 to run the program.
In gcc/g++ in Linux Compiler: To compile we can write command gcc main.c myfun.c -o main, gcc *.c -o main or gcc -o main *.c .
To Run: write command ./main


    Enter first number: 10
    Enter second number: 12
    Sum: 22
    Average: 11.000000

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.