Header file in C

In C, a header file is essentially a blueprint for your code. It stores declarations of functions, macros, and other information that multiple source files (.c) can access and share. Think of them as shared libraries containing the essential building blocks for your program.

Here’s how it works:

  • Include directive: You use #include directives in your source files to “include” the header file and make its contents accessible.
  • Example: #include <stdio.h> includes the standard input/output header, giving you access to functions like printf and scanf.
  • Benefits:
    • Code reuse: You can write code once in a header and use it across multiple source files, reducing redundancy and improving code maintainability.
    • Declaration separation: Keeps implementation details separate from declarations, making code cleaner and easier to understand.
    • Standardization: Header files like <stdio.h> provide standardized functionality, ensuring your code works consistently across different systems.

Here are some key points about header files in C:

  • They typically have the extension .h.
  • They can contain function prototypes, macro definitions, constant definitions, typedefs, and more.
  • They are not compiled directly but are included by source files.
  • Preprocessor directives like #ifdef and #ifndef can control which parts of a header file are included based on conditions.
  • Using header files effectively promotes code organization, maintainability, and clarity.

Standard Library Headers:

  • <stdio.h>: Provides basic input/output functionality (e.g., printfscanf).
    • printf and fprintf: Print formatted text to console or file.
    • scanf and fscanf: Read formatted input from console or file.
#include <stdio.h>

int main() {
  printf("Hello, world!\n"); // Print text to console
  int age;
  scanf("%d", &age); // Read integer input and store in 'age'
  printf("You are %d years old.\n", age); // Print with variable
  return 0;
}
  • <stdlib.h>: Offers general utilities like memory allocation (e.g., mallocfree) and random number generation (rand).
    • malloc and free: Allocate and deallocate memory dynamically.
    • rand: Generate random numbers.
#include <stdlib.h>

int main() {
  int* array = malloc(10 * sizeof(int)); // Allocate memory for 10 integers
  // Use the array...
  free(array); // Release allocated memory
  return 0;
}
  • <string.h>: Works with strings and their manipulation (e.g., strcpystrcatstrlen).
    • strcpy and strcat: Copy and concatenate strings.
    • strlen: Get the length of a string.
    • strcmp: Compare two strings.
#include <string.h>

int main() {
  char name1[] = "John";
  char name2[20];
  strcpy(name2, name1); // Copy "John" to name2
  strcat(name2, " Doe"); // Append " Doe" to name2
  if (strcmp(name1, name2) == 0) {
    printf("Strings are equal!\n");
  }
  return 0;
}
  • <math.h>: Provides mathematical functions (e.g., sincossqrt).
    • sincostan: Trigonometric functions.
    • sqrt: Square root.
    • pow: Exponentiation.
#include <math.h>

int main() {
  double area = M_PI * pow(5, 2); // Calculate area of a circle (M_PI from <math.h>)
  printf("Area of circle: %f\n", area);
  return 0;
}
  • <time.h>: Deals with time and date manipulation (e.g., timestrftime).
    • time: Get the current time as a long integer.
    • strftime: Format a time value into a string.
#include <time.h>

int main() {
  time_t current_time = time(NULL);
  struct tm *time_info = localtime(&current_time);
  char buffer[80];
  strftime(buffer, sizeof(buffer), "%H:%M:%S", time_info);
  printf("Current time: %s\n", buffer);
  return 0;
}

I/O Headers:


In C, I/O (input/output) headers are crucial for interacting with your program’s environment. Here are some of the most important ones and their functionalities, along with examples:

  • <stdio.h>: The cornerstone of C I/O, providing basic functions like:
    • Printing: printf and fprintf to print formatted output to console or files.
    • Reading: scanf and fscanf to read formatted input from console or files.
    • File access: fopenfclosefread, and fwrite for opening, closing, reading from, and writing to files.
    • Example:
#include <stdio.h>

int main() {
  printf("Enter your name: ");
  char name[50];
  scanf("%s", name); // Read a string into 'name'
  printf("Hello, %s!\n", name); // Print greeting with the read name
  return 0;
}
  • <stdlib.h>: Offers additional I/O functionalities:
    • Temporary files: tmpnam to create temporary filenames.
    • String manipulation: strtok to tokenize strings based on delimiters.
    • Error handling: perror to print system error messages.
    • Example:
#include <stdlib.h>

int main() {
  char buffer[1024];
  FILE* temp_file = tmpfile(); // Create a temporary file
  fprintf(temp_file, "This is some data to write..."); // Write data to the file
  rewind(temp_file); // Reset file pointer to the beginning
  fgets(buffer, sizeof(buffer), temp_file); // Read data into buffer
  printf("Read from temporary file: %s", buffer);
  fclose(temp_file); // Close and remove the temporary file
  return 0;
}
  • <unistd.h>: Provides more advanced I/O features:
    • Pipes and FIFOs: pipe and mkfifo to create communication channels between processes.
    • Process control: forkexec, and wait to manage child processes.
    • Terminal I/O: isatty and tcgetattr to interact with terminal settings.
    • Example:
#include <unistd.h>

int main() {
  int pipe_fds[2];
  pipe(pipe_fds); // Create a pipe
  pid_t child_pid = fork(); // Create a child process
  if (child_pid == 0) {
    dup2(pipe_fds[1], STDOUT_FILENO); // Redirect child's output to the pipe
    execlp("ls", "ls", "-l", NULL); // Execute 'ls' command and send output to the pipe
  } else {
    close(pipe_fds[1]); // Parent closes write end of the pipe
    char buffer[1024];
    read(pipe_fds[0], buffer, sizeof(buffer)); // Read child's output from the pipe
    printf("Child output:\n%s", buffer);
    close(pipe_fds[0]); // Parent closes read end of the pipe
  }
  return 0;
}

Remember, this is a glimpse into the world of C I/O headers. Explore their functionalities further and choose the ones that best suit your specific program’s needs.

When it comes to math-related functionalities in C, the essential header file is <math.h> This header provides a wide range of functions for performing common mathematical operations, including:

  • Trigonometric functions: sincostanasin, etc.
  • Exponential and logarithmic functions: exploglog10, etc.
  • Power functions: powsqrtcbrt, etc.
  • Rounding and flooring functions: floorceilround, etc.
  • Absolute value function: abs
  • Hyperbolic functions: sinhcoshtanh, etc.
  • Trigonometric functions: sincostanasin, etc.
  • Exponential and logarithmic functions: exploglog10, etc.
  • Power functions: powsqrtcbrt, etc.
  • Rounding and flooring functions: floorceilround, etc.
  • Absolute value function: abs
  • Hyperbolic functions: sinhcoshtanh, etc.

Here’s an example of using <math.h> to calculate the area of a circle:

#include <stdio.h>
#include <math.h>

int main() {
  double radius = 5.0; // Define the circle's radius
  double area = M_PI * pow(radius, 2); // Use M_PI from `<math.h>` and `pow` function

  printf("Area of the circle: %f\n", area);

  return 0;
}

This example demonstrates how to:

  • Include <math.h> and <stdio.h> headers.
  • Define a variable for the circle’s radius.
  • Use pow function from <math.h> to calculate the square of the radius.
  • Use M_PI constant (value of pi) defined in <math.h> to calculate the area.
  • Print the calculated area using printf from <stdio.h>.

Memory Management Headers:

  • <malloc.h>: Provides functions for memory allocation and deallocation (e.g., mallocfree).

String Formatting Headers:

  • <stdarg.h>: Allows variable number of arguments for functions (e.g., printf).

System-Specific Headers:

  • <unistd.h>: Provides POSIX-compatible functions for file I/O and process control (e.g., readwritefork).

Other Useful Headers:

  • <assert.h>: Defines the assert macro for debugging purposes.
  • <ctype.h>: Provides character classification functions (e.g., isdigitisalpha).
  • <limits.h>: Defines system-specific limits for integer types (e.g., INT_MAXINT_MIN).

Remember:

  • This is not an exhaustive list, and the appropriate header files will vary depending on your specific program’s needs.
  • It’s always best practice to consult the C standard library documentation for detailed information on available header files and their functionalities.

Remember: Choosing the right header files for your program depends on its specific needs.

See also:

Header file in C++

Share this post:

Newsletter Updates

Enter your email address below and subscribe to our newsletter