The Wayback Machine - https://web.archive.org/web/20241116032040/https://www.geeksforgeeks.org/header-files-in-c-cpp-and-its-uses/
Open In App

Header Files in C

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive “#include”.

C Header files offer the features like library functions, data types, macros, etc by importing them into the program with the help of a preprocessor directive “#include”.

Syntax of Header Files in C

We can include header files in C by using one of the given two syntax whether it is a pre-defined or user-defined header file.

#include <filename.h>    // for files in system/default directory
or
#include "filename.h" // for files in same directory as source file

The “#include” preprocessor directs the compiler that the header file needs to be processed before compilation and includes all the necessary data types and function definitions.

header files in C

C Header File

To learn how to organize your code efficiently using header files and data structures, the C Programming Course Online with Data Structures provides practical insights on modular programming.

Example of Header File in C

The below example demonstrates the use of header files using standard input and output stdio.h header file

C
// C program to demonstrate the use of header files
//    standard input and output stdio.h header file
#include <stdio.h>

int main()
{
    printf(
        "Printf() is the function in stdio.h header file");
    return 0;
}

Output
Printf() is the function in stdio.h header file

Types of C Header Files

There are two types of header files in C:

  1. Standard / Pre-existing header files
  2. Non-standard / User-defined header files

1. Standard Header Files in C and Their Uses

Standard header files contain the libraries defined in the ISO standard of the C programming language. They are stored in the default directory of the compiler and are present in all the C compilers from any vendor.

There are 31 standard header files in the latest version of C language. Following is the list of some commonly used header files in C:

Header File

Description

<assert.h>It contains information for adding diagnostics that aid program debugging.
<errno.h>It is used to perform error handling operations like errno(), strerror(), perror(), etc.
<float.h>

It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. 

They make programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc.

<math.h>It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.
<signal.h>It is used to perform signal handling functions like signal() and raise().
<stdarg.h>

It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the

variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively.

<ctype.h>

It contains function prototypes for functions that test characters for certain properties, and also function prototypes for 

functions that can be used to convert uppercase letters to lowercase letters and vice versa.
 

<stdio.h>It is used to perform input and output operations using functions like scanf(), printf(), etc.
<setjump.h>

It contains standard utility functions like malloc(), realloc(), etc. It contains function prototypes for functions that allow bypassing 

of the usual function call and return sequence.

<string.h>It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.
<limits.h>

It determines the various properties of the various variable types. The macros defined in this header limits the values of 

various variable types like char, int, and long. These limits specify that a variable cannot store any value 

beyond these limits, for example, an unsigned character can store up to a maximum value of 255.

<time.h>

It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date 

and get the CPU time respectively.

<stddef.h>It contains common type definitions used by C for performing calculations.
<locale.h>

It contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. 

It enables the computer system to handle different conventions for expressing data such as times, dates, or large numbers throughout the world.

Example

The below example demonstrates the use of some commonly used header files in C.

C
// C program to illustrate
// the use of header file
// in C
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Driver Code
int main()
{
    char s1[20] = "12345";
    char s2[10] = "Geeks";
    char s3[10] = "ForGeeks";
    long int res;

    // Find the value of 9^3 using a
    // function in math.h library
    res = pow(9, 3);
    printf("Using math.h, "
           "The value is: %ld\n",
           res);

    // Convert a string to long long int
    // using a function in stdlib.h library
    long int a = atol(s1);
    printf("Using stdlib.h, the string");
    printf(" to long int: %ld\n", a);

    // Copy the string s3 into s2 using
    // using a function in string.h library
    strcpy(s2, s3);
    printf("Using string.h, the strings"
           " s2 and s3: %s %s\n",
           s2, s3);
    return 0;
}

Output
Using math.h, The value is: 729
Using stdlib.h, the string to long int: 12345
Using string.h, the strings s2 and s3: ForGeeks ForGeeks

2. Non-Standard Header Files in C and Their Uses

Non-standard header files are not part of the language’s ISO standard. They are generally all the header files defined by the programmers for purposes like containing custom library functions etc. They are manually installed by the user or maybe part of the compiler by some specific vendor.

There are lots of non-standard libraries for C language. Some commonly used non-standard/user-defined header files are listed below:

Header FileDescription
<conio.h>It contains some useful console functions.
<gtk/gtk.h>It contains GNU’s GUI library for C.

Example

The below example demonstrates the use of conio.h non-standard header file.

C
#include <stdio.h>
#include <conio.h>

// Function to display a welcome message
void displayMessage() {
    printf("Hello! Geek\n");
}

int main() {
    // Using conio.h functions
    printf("Press any key to print message \n");
    getch();  // Wait for a key press

    // Call the additional function after a key press
    displayMessage();

    return 0;
}


Output

Press any key to print message 
Hello! Geek

Create your own Header File in C

Instead of writing a large and complex code, we can create our own header files and include them in our program to use whenever we want. It enhances code functionality and readability. Below are the steps to create our own header file:

Step 1: Write your own C code and save that file with the “.h” extension. Below is the illustration of the header file:

C
// Function to find the sum of two
// numbers passed
int sumOfTwoNumbers(int a, int b) 
{
  return (a + b); 
}


Step 2: Include your header file with “#include” in your C program as shown below: 

C
// C++ program to find the sum of two
// numbers using function declared in
// header file
#include "iostream"

// Including header file
#include "sum.h"
using namespace std;

// Driver Code
int main()
{

    // Given two numbers
    int a = 13, b = 22;

    // Function declared in header
    // file to find the sum
    printf("Sum is: %d", sumoftwonumbers(a, b));
}


Output

Sum is: 35

Including Multiple Header Files

You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used.

Syntax

#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
the entire header file
#endif

This construct is called wrapper “#ifndef”. When the header is included again, the conditional will become false, because HEADER_FILE_NAME is defined. The preprocessor will skip over the entire file contents, and the compiler will not see it twice.

Sometimes it’s essential to include several diverse header files based on the requirements of the program. For this, multiple conditionals are used.

Syntax

#if SYSTEM_ONE
#include "system1.h"
#elif SYSTEM_TWO
#include "system2.h"
#elif SYSTEM_THREE
....
#endif


Previous Article
Next Article

Similar Reads

What’s difference between header files "stdio.h" and "stdlib.h" ?
These are two important header files used in C programming. While “<stdio.h>” is header file for Standard Input Output, “<stdlib.h>” is header file for Standard Library. One easy way to differentiate these two header files is that “<stdio.h>” contains declaration of printf() and scanf() while “<stdlib.h>” contains declaratio
2 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
Comment in header file name?
What happens if there is a comment in header file name? Parsing of `#include' is slightly special because comments are not recognized within the ''. Thus, in `#include ' the `/*' does not start a comment and the directive specifies inclusion of a system header file named `x/*y'. Of course, a header file with such a name is unlikely to exist on Unix
1 min read
numeric header in C++ STL | Set 2 (adjacent_difference(), inner_product() and iota())
The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header: iotaaccumulatereduceinner_productpartial_sum etc. See this article for more reference: accumulate()
4 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question arises, is it possible to create your own header fil
4 min read
C Program to list all files and sub-directories in a directory
#include <stdio.h> #include <dirent.h> int main(void) { struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory" ); return 0; } // Refer http://pu
1 min read
Linking Files having same variables with different data types in C
Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c. Note that none of the variables is declared as extern. What do you expect to be the output of the following command with given two programs? $ gcc -o my
2 min read
Multiple Source Files in C
C programming language, as it is a procedural programming language sometime we need two or more programs linked together to store all the methods together. So, let's check how to link two C source files. Methods to compile multi-file c program are given below: Methods to use two or more source code files in C There are two methods to use two or mor
3 min read
C Program to merge contents of two files into a third file
Let the given two files be file1.txt and file2.txt. The following are steps to merge. 1) Open file1.txt and file2.txt in read mode. 2) Open file3.txt in write mode. 3) Run a loop to one by one copy characters of file1.txt to file3.txt. 4) Run a loop to one by one copy characters of file2.txt to file3.txt. 5) Close all files. To successfully run the
2 min read
C program to compare two files and report mismatches
We are given almost two identical files. But some characters are corrupted. We need to find the line number and their position where those corrupted letter exists as well as Total number of corrupted (error) letters. Examples: Input : file1.txt contains it is fun file2.txt contains it is run Output : Line Number : 2 Error Position : 1 Total Errors
2 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 25 C Projects with Source Codes for 2024
If you're looking for project ideas to boost your C Programming skills, you're in the right spot. Programming is about problem-solving and adapting to ever-changing technology. Start with C, the foundation of many modern languages, to refine your programming abilities. Despite being introduced 50 years ago, C remains a top choice for beginners due
14 min read
Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to the function are called actual parameters whereas the parameters received by the function are called formal parameters. Call By Value in CIn call by value
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the oldest and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating system
15+ min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Basics of File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do we need File Handling in C?So far the operations using the
15 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Additionally, the values of a structure are stored i
10 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. So basica
11 min read
Article Tags :
three90RightbarBannerImg