Skip to content
Home » C Programming » The C Basics » Source and Header Files

Source and Header Files

What are C Source Files?

A C application is primarily compiled and built from source and header files (.c and .h files). A source file normally contains application’s logic and implementation that performs certain tasks. A header file normally contains declaration and prototypes of your logic / functions implemented in the source file. A function prototype is important as it tells the compiler what input and output to expect from a function implementation.

This is an example of a source file (myfuncs.c) that implements 2 functions:

  • printfHelloWorld()
  • promptAndPrint()
/* myfuncs.c */
#include <stdio.h>

void printHelloWorld(void)
{
	printf("Hello World\n");
}

void promptAndPrint(void)
{
	int iNumber = 0;
	printf("Enter an integer please: ");
	scanf("%d", &iNumber);
	printf("You entered: %d", iNumber);
}

What are C Header Files?

This is an example of a header file (myfuncs.h) containing the function prototypes implemented in myfuncs.c. Other source files can gain access to these 2 functions by #include this header file.

/* myfuncs.h */

void printHelloWorld(void);
void promptAndPrint(void);

How to Include Other Header Files to Gain Access?

Another source file (myprogram.c) that contains the entry point (also known as the main() function) can gain access to both printHelloWorld() and promptAndPrint() functions simply by including the respective header file using the #include preprocessor clause. More on preprocessor here.

/* myprogram.c */
/* include standard C IO library */
#include <stdio.h>

/* include user-defined myfuncs.h */
#include "myfuncs.h"

int main(void)
{
	/* call the functions defined in myfuncs.c */
	printHelloWorld();
	promptAndPrint();
	return 0;
}

Join the conversation

Your email address will not be published. Required fields are marked *