Skip to main content

Header Files and their Examples in C

 

What Is A Header File In C?

A header file in C language is a text file containing definitions of functions, variables, and macros that are shared among multiple source files. It provides an interface to the variety of functions and data structures that can be used by other parts of the program. Essentially, a header file serves as a contract that specifies what features/ operations are available to the rest of the program without exposing the implementation details.



Standard Header File In C & Their Uses

In C, there are many standard header files, each of which has a unique collection of utilities and methods. Naturally, there are a few standard C header files that are most typically used in applications/ C code.  We have compiled a detailed explanation of all 25 standard header files in C.



The <stdio.h> Header File In C

The name stands for standard input/output header, and it contains functions for standard input and output operations such as printf() and scanf() and file operations like fopen(), fclose(), fseek(), fread(), and write(). This header file is used for printing information to the console, reading input from the keyboard, and reading and writing data to and from files.

Some standard functions that form a part of this header file are:

  1. printf(): Used to print formatted output to the console or a file.
  2. scanf(): Used to read formatted input from the console or a file.
  3. fgets(): Used to read a line of text from a file or the console.
  4. fopen(): Used to open a file.
  5. fclose(): Used to close a file.
  6. fseek(): Used to set the file position indicator for a file.
  7. fread(): Used to read data from a file.
  8. fwrite(): Used to write data to a file.

The <stdlib.h> Header File In C

The term stdlib.h stands for standard library header, which contains functions for general-purpose tasks such as memory allocation, process control, conversions, and searching.

  • It is mainly used to perform standard utility functions like malloc(), calloc(), realloc(), and free() for memory allocation and deallocation.
  • It also contains functions like rand() and srand() for generating random numbers and qsort() for sorting arrays.
  • All in all, this header file in C is used for memory management, number manipulation, and searching and sorting algorithms.

Some standard functions that form a part of this header file are:

  1. malloc(): Used to dynamically allocate memory.
  2. free(): Used to free dynamically allocated memory.
  3. atoi(): Used to convert a string to an integer.
  4. atof(): Used to convert a string to a floating-point number.
  5. rand(): Used to generate a random number.
  6. qsort(): Used to sort an array.

The <string.h> Header File In C

This header contains functions for string manipulation and memory manipulation. It includes functions like strlen(), strcpy(), strcat(), strstr(), and strtok() for string manipulation and memset(), memcpy(), and memcmp() for memory manipulation. In other words, it is used for working with strings and manipulating memory.

Some standard functions that form a part of this header file are:

  1. strlen(): Used to get the length of a string.
  2. strcpy(): Used to copy one string to another.
  3. strcat(): Used to concatenate two strings.
  4. strstr(): Used to find a substring in a string.
  5. memset(): Used to set the value of a block of memory to a specific value.
  6. memcpy(): Used to copy a block of memory from one location to another.

The <math.h> Header File In C

This header file contains mathematical functions such as trigonometric functions, logarithmic functions, and exponential functions. This includes functions like sin(), cos(), tan(), sqrt(), pow(), and ceil() for performing mathematical operations. The primary purpose of this header is to help in performing complex mathematical operations.

Some standard functions that form a part of this header file are:

  1. sin(): Used to calculate the sine of an angle.
  2. cos(): Used to calculate the cosine of an angle.
  3. tan(): Used to calculate the tangent of an angle.
  4. sqrt(): Used to calculate the square root of a number.
  5. pow(): Used to raise a number to a power.
  6. ceil(): Used to round a number up to the nearest integer.
  7. floor(): Used to round a number down to the nearest integer.

Sample of header files in C

The <time.h> Header File In C

As the name suggests, this header file contains functions for time manipulation and conversion. Such as functions like time(), localtime(), and strftime() for getting the current time, converting time to string, and formatting time. It makes it possible to work with dates and times.

Some standard functions that form a part of this header file are:

  1. time(): Used to get the current time in seconds since the Epoch.
  2. localtime(): Used to convert a time value to a local time.
  3. gmtime(): Used to convert a time value to a UTC time.
  4. mktime(): Used to convert a local time to a time value.
  5. strftime(): Used to format a time value as a string.

The <ctype.h> Header File In C

The header file contains functions for character type checking and case conversion. For example, isdigit(), isalpha(), toupper(), and tolower() for checking the type of characters and converting cases. It is used for working with characters and strings.

Some standard functions that form a part of this header file are:

  1. isdigit(): Used to check if a character is a digit.
  2. isalpha(): Used to check if a character is an alphabetic character.
  3. islower(): Used to check if a character is a lowercase letter.
  4. toupper(): Used to convert a character to uppercase.
  5. tolower(): Used to convert a character to lowercase.

The <errno.h> Header File In C

The errno.h header file consists of the global variable errno, which is used to indicate errors during program execution. It contains functions like perror(), which is used to print error messages based on the current value of errno. The primary purpose of this header is to facilitate the handling errors in a program. 

The two primary standard functions that form a part of this header file are:

  1. errno: This is a global variable set to a value that indicates the type of error that occurred during program execution.
  2. perror(): Used to print an error message to the console based on the current value of the errno variable.

The <limits.h> Header File In C

This header file contains constants that represent the minimum and maximum values that can be stored in certain data types. Constants like CHAR_BIT, SCHAR_MIN, SCHAR_MAX, SHRT_MIN, and SHRT_MAX for different data types are a part of this header. It is used for checking the limits of data types.

Some standard library macros that form a part of this header file are:

  1. INT_MAX: The maximum value that can be stored in an int.
  2. INT_MIN: The minimum value that can be stored in an int.
  3. LONG_MAX: The maximum value that can be stored in a long int.
  4. LONG_MIN: The minimum value that can be stored in a long int.

The <float.h> Header File In C

The float.h file contains constants representing the minimum and maximum values that can be stored in floating-point data types. These constants include FLT_MIN, FLT_MAX, DBL_MIN, and DBL_MAX for different floating-point data types. In short, the float. h file is used to check the limits of floating-point data types.

Some standard functions/ library macros contained in this header file are:

  1. FLT_MAX: The maximum value that can be stored in a float.
  2. FLT_MIN: The minimum value that can be stored in a float.
  3. DBL_MAX: The maximum value that can be stored in a double.
  4. DBL_MIN: The minimum value that can be stored in a double.

The <assert.h> Header File In C

The file contains the assert() macro, which is used to check the validity of an expression during program execution. If the expression is evaluated to be false, the program terminates with an error message. This file is included for the purpose of debugging and error-checking during program execution. The primary function that is a part of this file is-

  1. assert(): Used to check a condition and terminate the program if the condition is false.

The <setjmp.h> Header File In C

The two primary functions in this header are the setjmp() and longjmp() functions, which are used for non-local jumps in a program. It is used for handling exceptions and other error conditions in a program.

The purpose of the standard functions that form a part of this header file are:

  1. setjmp()- This function saves the current execution state of a program in a buffer and returns zero.
  2. longjmp()- This function restores the saved state to the point where setjmp() was called, and returns control to that point in the program.

The <signal.h> Header File In C

As is evident by the name, this header contains signal handling functions, which are interrupts sent to a program by the operating system.

The standard functions that form a part of this header file are:

  1. signal() is used to handle signals received during runtime by registering a signal handler function
  2. raise() is used to simulate the sending of a signal to a process for testing purposes.

The <stdarg.h> Header File In C

This file is used to perform standard argument functions as it contains functions for handling variable arguments. These refer to the arguments passed to a function whose number and types are unknown at compile time. It contains macros like va_start(), va_arg(), and va_end() for handling variable arguments. In other words, this header is used when we want to work with functions that take variable arguments, like printf().

The standard functions contained in this header file are:

  1. va_start(): This function initializes an argument list for access by the va_arg() macro.
  2. va_arg(): This macro expands to an expression that retrieves the next argument from the argument list initialized by va_start().

The <stdbool.h> Header File In C

The <stdbool.h> stands for standard boolean header, and as is obvious, it is used when working with boolean data types. It contains definitions for boolean data types, which can only have the values true and false. In other words, it defines the macros for true and false.

The standard functions that form a part of this header file are:

  1. bool: This is a data type that is defined in this header file, and it can take two values, i.e., true or false.
  2. true and false: These are predefined constants of type bool that represent the boolean values.

The <stdint.h> Header File In C

It contains definitions for integer data types with specific bit widths. For example, types like int8_t, int16_t, int32_t, uint8_t, uint16_t, uint32_t, and others. In short, this header is included when we want to work with integer data types with specific bit widths.

The standard functions that form a part of this header file are:

  1. Integer data types: This header file defines integer data types with a fixed width, such as int8_t, int16_t, uint32_t, etc. This ensures the size and range of these data types across different platforms and compilers.
  2. Limits and constants: The stdint.h also defines various constants, such as INT_MAX, INT_MIN, UINT_MAX, etc., that provide information about the maximum and minimum values of integer data types.

The <locale.h> Header File In C

The primary purpose of this header is to facilitate and handle localization. This includes aspects like local languages and region-specific settings for formatting data like dates, times, and numbers. It contains two primary functions that help with the localization of data.

The standard functions contained in this header file are-

  1. setlocale(): This function helps change or retrieve the current locale. The two inputs this function takes are the category of the locale to set or get and the locale name.
  2. localeconv(): This function is used to obtain details about the formatting standards of the current locale, including the character for the decimal point and the currency sign. It gives back a pointer to a struct that has this data.

The <stddef.h> Header File In C

This header contains definitions for basic data types and macros for working with memory. It defines the types ptrdiff_t, size_t, wchar_t, etc., and the macros NULL and offsetof(). In short, it is used for purposes relating to the memory and basic data types.

The macros that belong to this header file are:

  1. size_t: This is a type used for expressing an object's size. It is frequently used as the return type for functions like strlen() and sizeof() that return the size of an object or buffer.
  2. NULL: This constant pointer value normally denotes a null pointer. It is frequently used to show that a valid pointer is missing, for example, when a function fails to allocate memory.

The <time.h> Header File In C

This header file is used when working with dates and times, as it contains functions for time manipulation and conversion. It defines variable types like size_t, clock_t, etc., and includes functions like time(), localtime(), and strftime() for getting the current time, converting time to string, and formatting time, respectively.

The standard functions that form a part of this header file are:

  1. time(): This function calculates the current time as the duration of time since the Epoch (0:00:00 UTC, January 1, 1970) and returns that value. Its parameter is a pointer to a time_t object, where the returned time value is kept.
  2. localtime(): This function is used when one wants to change a time value (expressed as the number of seconds since the Epoch) into local time, which corresponds to the time zone in which the program is currently running. It accepts a pointer to a time_t object as a parameter, and as a response, it returns a pointer to a struct tm object that holds the local time components.

The <wchar.h> Header File In C

The purpose of this header file is to facilitate working with wide characters, i.e., characters that use more than one byte to represent. It contains functions for working with wide characters such as fgetwc(), fputwc(), and wctype().

The common components of this header file are:

  1. wchar_t: This data type is defined in wchar.h header file and is used to represent wide characters that cannot be represented by a regular char data type. 
  2. Functions for wide character handling: This library also provides a set of functions for wide character handling, such as converting between multibyte and wide character strings, formatting wide character strings, and more. For example, int wcscmp()function that compares two wide character strings.

The <wctype.h> Header File In C

Contains functions for classifying wide characters, which are characters that use more than one byte to represent. It is used to work with these wide characters and functions like iswalpha(), iswdigit(), and iswpunct() for checking the type of wide characters.

Some standard functions that form a part of this header file are:

  1. wctype() is used to obtain a wide character classification object that represents a character class.
  2. iswctype() is used to test whether a given wide character belongs to a specific character class represented by a given wide character classification object.

The <complex.h> Header File In C

This header is used for performing complex mathematical operations with complex numbers, i.e., numbers that have both a real and imaginary part. It defines functions such as cabs(), cexp(), and cpow().

Some standard functions that belong to this header file are:

  1. creal() and cimag(): These functions are used to extract the real and imaginary parts of a complex number, respectively.
  2. cexp() and cpow(): These functions are used to perform complex exponentiation and complex power operations, respectively.

The <fenv.h> Header File In C

The use of this header file helps in controlling the behavior of floating-point operations. It contains functions for working with floating-point environments, which include things like rounding mode, floating-point exceptions, and floating-point precision. These functions include fesetround(), fegetround(), and feclearexcept().

Common standard functions from this header file are:

  1. fegetenv(): This function saves the current floating-point environment into the provided fenv_t object.
  2. fesetround(): This function sets the rounding direction mode for floating-point arithmetic operations.

The <inttypes.h> Header File In C

Another important header file, it consists of definitions for integer data types with specific bit widths, along with their corresponding printf() format specifiers. In other words, it is used when working with integer data types with specific bit widths and formatting them for output.

Common components of the inttypes.h header file are:

  1. PRId64: A format specifier used for int64_t data type in the printf() statements to print a signed 64-bit integer.
  2. strtoimax(): A function that converts a string to an integer of type intmax_t, which is a signed integer type with the maximum width supported by the implementation.

The <stdalign.h> Header File In C

This header file deals with the process of specifying how memory should be aligned. It contains definitions for alignment control with macros like alignas() and alignof() for specifying and querying alignment. Its primary purpose is to control the alignment of memory.

The common components that belong to this header file are:

  1. alignof: This macro returns the required alignment of a type in bytes.
  2. alignas: This specifier is used to specify the alignment of a variable or a structure field.

The <tgmath.h> Header File In C

The <tgmath.h> file defines macros for performing mathematical operations that work with both real and complex numbers. These macros include acos(), asin(), atan(), cos(), sin().

Some standard functions that form a part of this header file are:

  1. sin(x): which returns the sine of `x`, where `x` is a floating-point number of any type.
  2. sqrt(x): which returns the square root of `x`, where `x` is a floating-point number of any type.

For the most part, these standard header files offer a large range of utilities and functions that are crucial for C programming. These header files give you access to a wealth of functionality that can make programming chores easier. You can use this capability by including these header files in your code.

Examples Of Using Header Files In C

Using standard header files in C gives us access to a wide range of capabilities when included in the code/ program, thus making the job of a programmer easier. Let's take a look at examples showcasing the application of all the header files we discussed above. 

Code Example 1:

Output:

Hello world!
str2: Hello
The square root of 4.000000 is 2.000000
Current time: Tue Nov 14 11:16:29 2023

Explanation:

  1. This C code demonstrates the usage of various standard library headers in C programming, including-
    • <stdio.h> for input/output operations.
    • <stdlib.h> for memory allocation and management.
    • <string.h> for string manipulation.
    • <math.h> for mathematical operations, including square root calculation.
    • <time.h> for date and time functions.
  2. After including all the header files, we initiate the main() function. Inside the function-
    • We use the printf() function from <stdio.h> to print Hello world! to the console.
    • Then, we declare an array of integers and allocate memory to it, using the malloc() function from the <stdlib.h> file.
    • Next, we use the <string.h> header to declare two character arrays/ string, i.e., s1 (initialized to Hello) and s2[6]. We use functions strcpy() and printf() to manipulate character arrays, copy the content from one array to another, and display the result.
    • After that, we use the sqrt() function from <math.h> to calculate the square root of a number (variable a=4.0) and display the result using printf.
    • Lastly, we use the function from <time.h> file to get and display the current time in a human-readable format.

The code comments in the example above indicate the name of the header file being used for the respective operation/ purpose. 

Code Example 2:

Output:

Z is an alphabetic character.
x is true.
The max value of an int is 2147483647
The min value of a float is 1.175494e-38
main: assertion `a > 10' failed
Error in opening file

Explanation:

The code demonstrates the use of various standard C libraries for character classification, boolean data types, limits, floating-point constants, assertion checks, and error handling. We begin by including the header files and then inside the main() function-

  1. We use the function from <ctype.h> to check if the character variable (c) declared and initialized to Z is an alphabetic character and print a message accordingly.
  2. Next, we use the <stdbool.h> file to define a boolean variable x, initialize it as true, and print a message based on its value.
  3. Then, using the <limits.h> and <float.h> header files, we print the maximum value of an integer (INT_MAX) and the minimum value of a floating-point number (FLT_MIN).
  4. After that, we use the assert() function from the <assert.h> header, to check if the integer variable a, assigned to 2, is greater than 10. An assertion failure will occur if the condition is not met.
  5. Lastly, we use <errno.h> header operations in conjunction with file operations. We attempt to open a non-existent file and check for an error when opening the file. If an error occurs, the printf() function outputs an error message with details.

Non-Standard Header Files In C & Their Uses

Non-standard header files are those produced by programmers for particular purposes, such as including customized library functions, and are not part of the language ISO standard. Also referred to as user-defined header files, these do not come automatically installed with the language. Instead, they must be installed individually by the user or may be provided as part of the compiler by specific vendors.

Header File

Description

<conio.h>

A number of helpful functions that may be utilized for console input and output operations are contained in this non-standard header file.

<gtk/gtk.h>

Access to the GNU graphical user interface (GUI) library for the C programming language is made possible via this non-standard header file.

Code Example:

Output:

It will be printed First!!

Explanation:

We begin the code by including the standard C library for input/output operations, i.e., <stdio.h>. Also included is a non-standard <conio.h> library, which is used for console-based operations in older C environments but may not be supported in modern compilers.

  1. We then define the main() function, the program's entry point.
  2. Next, we use the printf() function two times to print text to the console.
  3. After that, we use the clrscr() function from <conio.h> to clear the console screen, and once again use printf() to print another phrase to the console. 
  4. The program ends, returning 0 to indicate successful execution.

Note: The code includes the <conio.h> header, which is not a standard C library and may not be available on all systems.

How The Include Operation Works With Header Files In C?

Working of the include operation and header files in C | Flow-chart

The C preprocessor is instructed to scan the file given as input before moving on to the remaining part of the current source file using the #include directive. Before continuing with the rest of your current source file, C's #include directive statement seeks to search through the C preprocessor for a particular file, such as input. The output generated by the preprocessor is composed of the output that has previously been produced, the output from the included file, the output from the text following the #include directive, and finally the output.

Let's use a scenario where you consider having a header file called file.h. The following sentence appears in the code/ syntax-

char *file (void);

The primary C source program then appears to be something as follows:

Code Example:

Output:

Completed

Explanation:

The code starts by including the <stdio.h> header file in C program. Then-

  1. We declare a global variable z, of integer type.
  2. Next, we include the header file, i.e., file.h, which is declared locally in the program or in a separate file.
  3. In the main() function, we call the printf() function and pass a string to it as input. This prints the message 'Completed' to the output window.

Code Example:

Output:

Successfully

Explanation:

The code begins with the header file stdio.h, after which we declare a global variable q of type int.

  1. Next, we declare a function file that returns a pointer to a character, but this function is not called in the main function.
  2. In the main() function, we call the printf() function to print the message/ strong 'Successfully' to the output window.
  3. Since there are no errors in the code, the program will execute Successfully.

Once-Only Header Files In C

Programmers utilize this method to avoid redefinition mistakes and conflicting declarations that might occur when header files are included numerous times in the same source code file (Entire file contents).

  • This method is implemented using preprocessor directives like #ifndef, #define, and #endif to ensure that a header file is only included once.
  • If a header file's contents are included more than once, the compiler will process them twice, leading to a compilation error.
  • The conventional method for preventing this is to enclose the complete real contents of the executable file with a conditional, as seen below.

#ifndef HEADER_FILE
#define HEADER_FILE

the complete header file file

#endif

This is frequently referred to as a wrapper #ifndef. Because HEADER_FILE is defined, the conditional will be false when the header is included again. The preprocessor will skip through the entire file contents, and the compiler will not see it twice.

Comments

Popular posts from this blog

Structures and Union in C

  Structures and Unions Introduction: Structures and unions are composite data types in C that allow the grouping of multiple variables of different data types under a single name. They provide a way to represent complex data structures in a program, making it easier to organize and manipulate data. Definition: Structure: A structure is a collection of variables (of different data types) grouped together under a single name. Each variable within a structure is called a member or field. Structures enable the creation of custom data types to represent real-world entities. They are defined using the struct keyword. Union: A union is similar to a structure in that it also groups variables of different data types under a single name. However, unlike structures, unions allocate memory that is only as large as the largest member. This means that only one member of the union can be accessed at a time. Unions are useful when memory conservation is a concern, and only one member needs to b...

Recursive Functions in C

  Lecture Notes: Recursive Functions in C Introduction to Recursive Functions: Recursive functions are functions that call themselves directly or indirectly to solve a problem by dividing it into smaller instances of the same problem. They are a powerful programming technique used to solve problems that can be broken down into simpler subproblems. Definition: A recursive function is a function that calls itself either directly or indirectly during its execution. Types of Recursive Functions: Direct Recursion: In direct recursion, a function calls itself directly. c Copy code // Example of direct recursion void countdown ( int n) { if (n > 0 ) { printf ( "%d " , n); countdown(n - 1 ); // Recursive call } } Indirect Recursion: In indirect recursion, a function calls another function, which in turn calls the first function, creating a cycle of function calls. c Copy code // Example of indirect recursion void func1 ( int n) ; void func2 ( ...