Header Files In C/C++ And Its Uses

Header Files In C/C++ And Its Uses

Header files are an essential part of both programming languages, and they serve as a means to include predefined standard library functions, data types, macros, and other features in your programs.In C, header files typically have the “.h” extension, and you include them in your code using the #include preprocessor directive. These header files provide access to various libraries and functions to simplify programming.

In C++, header files may or may not have the “.h” extension. The #include directive is used to import these header files and access the features they provide, including library functions, data types, and macros.These preprocessor directives are vital in both languages, as they ensure that the necessary header files are processed before the actual compilation, making the required features available for your code.

Syntax Of Header File In C/C+

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

The #include directive instructs the compiler to process the specified header file before the actual compilation of the source code. This includes making available all the necessary data types, function definitions, and other declarations contained within the included header file for use in your program. It allows you to access predefined functionality and libraries to simplify your programming tasks.


// 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 Header Files

There are two types of header files in C and 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 libraries and functions that are defined in the ISO standard of the C programming language. These header files are typically stored in the default directory of the C compiler, making them universally accessible and present in all C compilers from different vendors. This standardization ensures that C programs can be written and compiled consistently across different platforms and compilers, making it a powerful feature of the C programming language.

There are 31 standard header files in the latest version of C language.

Header FileDescription
<assert.h>It has information regarding adding diagnostics that aid program debugging.
<errorno.h>It has to perform error-handling operations like errno(), strerror(), perror(), etc.
<float.h>It has to perform error-handling operations like errno(), strerror(), perror(), etc.
<math.h>It has to perform mathematical operations like sqrt()log2()pow(), etc.
<signal.h>It has to perform signal handling functions like signal() and raise().
<stdarg.h>It has to perform standard argument functions like va_start() and va_arg(). Moreover, they are used to indicate the start of the variable-length argument list and to get the arguments from the variable-length argument list in the program respectively.
<ctype.h>It has function prototypes for functions that will test characters for certain properties and also function prototypes for functions that will be used to convert uppercase letters to lowercase letters and vice versa.
 
<stdio.h><stdio.h> functions to perform input and output operations using functions like scanf()printf(), etc.
<setjump.h>It even 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 determines the various properties of the various variable types. The macros defined in this header limit 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.
<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 will 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 will contain common type definitions used by C for performing calculations.
<locale.h>It will contain 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

/ 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: Skill Vertex

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

Non-standard header files are not part of the ISO standard of the C programming language. These header files are typically created by programmers for various purposes, such as containing custom library functions or platform-specific code. They are not part of the standard library and are not guaranteed to be available on all C compilers.

Non-standard header files can be manually installed by the user, included as part of a third-party library, or provided by specific vendors. Their use is often limited to specific projects or platforms and may not be portable across different environments or compilers.

 Some commonly used non-standard/user-defined header files are listed below:

Header FileDescription
<conio.h>It has some useful console functions.
<gtk/gtk.h>It has some useful console functions.

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

Non-standard header files are not included in the official ISO standard for the C programming language. These header files are typically created by programmers for various purposes, including custom library functions or platform-specific code. They are not guaranteed to be universally available, and their use is often limited to specific projects, user installations, or specific compiler distributions by certain vendors. Non-standard header files provide a way to extend the functionality of C for specific use cases but may not be portable across different environments or compilers.

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

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

Standard Header Files in C++ and their Uses

Standard header files in C++ contain libraries and functionalities that are part of the C++ ISO standard. These header files come pre-installed with the C++ compiler from any vendor, ensuring that they are universally available for C++ programmers.

You can include these standard header files in your C++ programs using the #include preprocessor directive. This allows you to access the standard libraries, data types, and functions defined by the C++ ISO standard in your code, making it easier to write portable and standardized C++ programs across different platforms and compilers.

C language’s Standard Libraries are the following

Header FileDescription
<iostream>It has a stream of Input and Output using cin and cout.
<iomanip>It has a stream of Input and Output using cin and cout.
<fstream>It functions to control the data to read from a file as an input and data to write into the file as an output.
<algorithm>It has some useful algorithms which are part of STL.
<new>It has a dynamic memory allocation methods.
<vector>It has the definition of the vector class container of STL.
<map>It has a dynamic memory allocation method.

Example



// C++ program to demonstrate the use of standard header
// files in c++
#include <iostream>
#include <vector>
 
using namespace std;
 
// driver code
int main()
{
    // cout is defined in <iostream>
    cout << "Using iostream's cout to print" << endl;
 
    // vector defined in <vector> header file
    vector<int> v{ 11, 12, 14 };
 
    cout << "Using vector container: ";
    for (auto i : v) {
        cout << i << " ";
    }
    return 0;
}

Output

Using iostream's cout to print
Using vector container: 11 12 14

Non-Standard Header Files in C++ and Their Uses

Non-standard header files are not included in the ISO standard of C++, and they are typically created by programmers for their specific needs. These header files are not part of the official standard library and are not guaranteed to be universally available.

Non-standard header files can be manually installed by the user or included as part of a specific compiler distribution by a vendor. They are often used to extend the functionality of C++ for particular projects, but their availability may be limited to specific environments or compilers.

some non-standard header files in C++

Header FileDescription
<bits/stdc++.h>It has all the standard libraries of the header files mentioned above. However, if you include it in your code, then you need not have to include any other standard header files. But as it is a non-standard header file of GNU C++ library, so, if you try to compile your code with some compiler other than GCC it might fail; e.g. MSVC does not have this header.
<Qpushbutton>It has a push button element of Qt GUI Library for C++

Example

// C++ program to illustrate the use of
// non-standard bits/stdc++.h header file in C++
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
 
    char s1[20] = "12345";
    char s2[10] = "Geeks";
    char s3[10] = "ForGeeks";
    long int res;
 
    // All the below function are mentioned in bits/stdc++.h
    // library Find the value of 9^3
    res = pow(9, 3);
    cout << "Using bits/stdc++.h, "
            "The value is: "
         << res << "\n";
 
    // Convert a string to long long int
    long int a = atol(s1);
    cout << "Using bits/stdc++.h, the string";
    cout << " to long int: " << a << "\n";
 
    // Copy the string s3 into s2 using
    strcpy(s2, s3);
    cout << "Using bits/stdc++.h, the strings"
            " s2 and s3: "
<< s2 << s3 << "\n";
 
    return 0;
}

Output

Using bits/stdc++.h, The value is: 729
Using bits/stdc++.h, the string to long int: 12345
Using bits/stdc++.h, the strings s2 and s3: Skill Vertex

Create your own Header File in C and C++

Custom header files are a useful way to organize and modularize your code, making it more readable and maintainable. The steps you provided for creating a custom header file are generally correct:

  1. Write your own C/C++ code and save it with a “.h” extension. This is how you create the header file, and it typically contains function declarations, data type definitions, and other declarations that you want to use in multiple parts of your program.

By following this process, you can create your own reusable code modules, which can enhance code functionality, improve code organization, and make your programs more readable and manageable. These custom header files are included in your programs using the #include preprocessor directive, allowing you to access the declared functions and data types when needed.


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

Step 2: We have to include your header file with “#include” in your C/C++ program as provided



// 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
Process returned  0  (O x O) execution time:  0.287 s 
Press any key and continue

Including Multiple Header Files

When you include a header file more than once in a program, the contents of the header file are processed multiple times, which can lead to errors due to redefinition of symbols and declarations. To prevent these errors, conditional preprocessor directives, such as #ifndef, #define, and #endif, are commonly used to ensure that the header file is only processed once.

Syntax:

#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME

the entire header file

#endi

This construct is referred to as the wrapper “#ifndef”. Whenever the header is included again, the conditional will be false, as  HEADER_FILE_NAME will be defined. The preprocessor will skip over the entire file contents, and the compiler will not see it twice.

Sometimes it’s important to have several diverse header files based on the requirements of the program. For this, multiple conditionals will be used.

Syntax:

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

FAQ- Header Files In C/C++ And Its Uses

Q1. What are header files in C++ and their use?

Ans. Header files in C++ offer code reusability, organization, and complexity reduction. They allow you to declare functions and data types once and use them in various parts of your program, simplifying code and reducing errors.

Q2. Can C header files be used in C++?

Ans.When including a C header file in a C++ program, you may need to use the extern "C" construct to inform the C++ compiler that the functions declared in the header file are C functions. This is necessary because C and C++ have different name mangling conventions, and using extern "C" ensures that the functions are treated as C functions with C linkage, making them compatible with C++ code.

Q3. What are the header files in C and their function?

Ans. Header files in C have the “.h” extension and contain function declarations and macros for sharing among different source files. There are two types: custom ones created by programmers and standard ones provided by the compiler for common functionality.


Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment