How To Create Your Own Header Files In C

Step-1: Make a new file with the ".h" extension.

Begin by giving a unique name to a new text file with the extension ".h" to commence the process. As an example, you could name it "my header.h".

Step-2: Add header guards

Header guards prevent the header file from being included multiple times within a single compilation unit. They ensure that the contents of the header file are included only once. Include the following lines at the start and end of your header file to implement header guards.

Example

#ifndef MYHEADER_H
#define MYHEADER_H
// Your declarations and code go here
#endif // MYHEADER_H

Step-3: Add your Declarations

Within the header files, you have the freedom to include any declarations that you wish to maintain consistently across all your source files. Typically, header files encompass declarations such as function prototypes, struct definitions, constant values, and external variables.

Let's consider the subsequent example to demonstrate the process of squaring a numerical value and calculating the speed of light by utilizing a function:

Example

#ifndef MYHEADER_H
#define MYHEADER_H
//Function prototype
int calculateSquare(int num);
// Constant declaration
extern const double SPEED_OF_LIGHT;

#endif // MYHEADER_H

Step 4: Include the Header in your source files

Import the header file at the start of each source file to access the declarations from your header file in your C source code.

For instance, you can execute the following steps to incorporate your "myheader.h" header file into your "main.c" source file:

Example

#include "myheader.h"
int main() {
    int result = calculateSquare(5);
printf("Square of 5 is: %d\n", result);
    return 0;
}

Step-5: Compile your code

Include the necessary header file and all essential source files during the compilation of your C code. For example, you can compile both "main.c" and "myheader.h" concurrently in the following manner:

Example

gccmain.c -o my_program

Step-6: Run the code

Example

./my_program

Step-7: Output

Example

Square of 5 is: 25
Speed of Light: 299792458.000000 m/s

Explanation:

  • The function prototype for calculateSquare and the external definition of the constant variable SPEEDOFLIGHT are found in the header file "header.h" .
  • The "my functions.c" contains an implementation of the function calculateSquare that computes the square of a specified number.
  • The definition of the constant variable SPEEDOFLIGHT in "constants.c" is 0 , and the speed of light is measured in meters per second .
  • The main function uses the header file in "main.c", which uses the constant variable SPEEDOFLIGHT and the function calculateSquare .
  • After the source files are combined, the executable "my_program" is produced.
  • Upon execution, the program uses the calculateSquare function to get the square of the integer 5 , displaying the result and the value of the constant variable SPEEDOFLIGHT .
  • Your code has been successfully implemented using separate source files for functions and constant variables.
  • Complexity Analysis:

Time Complexity:

The time complexity of this particular function is O(1) . This function computes the square of the given input num by performing a single operation, which is multiplication. Since the number of operations remains constant regardless of the magnitude of num , the time complexity is O(1) .

Space Complexity:

  • This function's space complexity is O(1) . There are no dynamic memory allocations or recursive function calls in the function; instead, a fixed amount of memory is used to store the local variable num . Hence, the space complexity is constant.
  • The constant variable SPEEDOFLIGHT is a double with an O(1) space complexity . The constant variable has a fixed memory footprint independent of any inputs or problem size.
  • The main function in "main.c" also has an O(1) space complexity . There are no recursive calls or dynamic memory allocations in the main function, which stores local variables like num and square in a fixed amount of memory.
  • As the complete program only utilizes a fixed amount of memory that does not change depending on the input size, its overall space complexity is also O(1) .
  • Program:

Let's consider a program to grasp the concept of generating custom header files in the C programming language.

Example

#include <stdio.h>
//Header file
#ifndef OPERATIONS_H
#define OPERATIONS_H

// Constant declaration
#define PI 3.14159
//Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
double divide(double a, double b);
#endif // OPERATIONS_H
//Function to add two numbers
int add(int a, int b) {
    return a + b;
}
//Function to subtract two numbers
int subtract(int a, int b) {
    return a - b;
}
//Function to multiply two numbers
int multiply(int a, int b) {
    return a * b;
}
//Function to divide two numbers
double divide(double a, double b) {
    return a / b;
}
int main() {
    int num1 = 15, num2 = 5;
printf("The value of PI: %.5f\n", PI);
printf("The value of (10 + 7): %d\n", add(10, 7));
printf("The value of (20 - 9): %d\n", subtract(20, 9));
printf("The value of (8 * 6): %d\n", multiply(8, 6));
printf("The value of (12 / 3): %.2f\n", divide(12.0, 3.0));
    return 0;
}

Output:

Output

The value of PI: 3.14159
The value of (10 + 7): 17
The value of (20 - 9): 11
The value of (8 * 6): 48
The value of (12 / 3): 4.00

Explanation:

  • The program includes the standard input-output library h to use functions like printf .
  • The program defines a header file "operations.h" using preprocessor directives #ifndef, #define , and #endif . It prevents multiple header file inclusions in the same compilation unit.
  • Inside the header file, we have the following actions:
  • A constant declaration # defines PI 3.14159 and a macro PI with the value 14159 .
  • It contains prototypes for the four operations of addition, subtraction, multiplication , and division .
  • After that, we put the four functions addition, subtraction, multiplication , and division into effect below the header file. Every function executes the appropriate arithmetic operation and returns the output.
  • The following actions are carried out in the main function:
  • Print the value of PI using the printf function with format specifier %f to display the constant value with five decimal places.
  • Call the add, subtract, multiply , and divide functions with different arguments and print their results using the printf function.
  • Finally, the program returns 0 to indicate successful execution.
  • Complexity Analysis:

Time Complexity: O(1)

The time complexity remains constant as each function executes operations that take the same amount of time, independent of the input's size.

Space Complexity: O(1)

The software consumes a set quantity of memory that remains unaffected by the input's size. Therefore, the space complexity remains constant.

Characteristics:

There are numerous attributes associated with header files. A few key characteristics include:

The program demonstrates basic user interaction by utilizing the printf function to showcase the outcomes of mathematical calculations. This functionality enables users to engage with the program and view the computed results. Numerous software applications rely on uncomplicated user interaction to provide users with feedback and valuable data.

Reusability is enhanced by employing a distinct header file containing function prototypes. By declaring functions in the header file, they can be utilized in other source files without the need for redefinition. This approach promotes the "Don't Repeat Yourself" (DRY) principle, minimizing code redundancy and promoting a more organized and maintainable codebase. Leveraging reusability minimizes code duplication and streamlines future code adjustments when multiple program sections require identical functionality.

The program's adaptability is enhanced by its modular structure and the integration of functions. This design allows for easy customization and expansion of features, thanks to the clear distinction of responsibilities. To introduce new arithmetic operations or constants, one simply needs to include them in the header file and define their functionality in the appropriate source file. This level of flexibility empowers the program to grow and adjust to evolving demands without requiring significant code alterations.

Effortless Running: The execution process of the program is uncomplicated, which is ideal for scenarios with small and constant input sizes. Developers find the code easier to understand and manage as it eliminates unnecessary intricacies and focuses on fundamental mathematical tasks. This straightforward execution also aids in debugging and pinpointing any issues within the program.

Modularization: The C language program streamlines modularization by employing a distinct header file named "operations.h" for specifying constants and function prototypes. This header file acts as an intermediary by segregating the declarations from the implementations. Through this modular methodology, programmers can independently manage different segments of the codebase, enhancing the structure and sustainability of the code. Modularization also aids in isolating modifications as the program grows, thereby minimizing the chances of introducing errors in other sections of the codebase.

Input Required

This code uses input(). Please provide values below: