Header Files in C

Header Files in C

A header file is a file with the extension .h that contains:

  • C function declarations

  • Macro definitions

  • Shared constants and variables

These are used to share code between multiple source files.


Types of Header Files

There are two types of header files:

  1. System Header Files

    • Provided with the compiler

    • Example: stdio.h

  2. User-Defined Header Files

    • Written by the programmer

    • Used to organize project-specific declarations


Including a Header File

You can include a header file using the C preprocessor directive:

#include

Including a header file is equivalent to copying its contents into your source file.
However, manually copying code is:

  • Error-prone

  • Hard to maintain

  • Not recommended, especially for multi-file programs


Common Practice

A standard practice in C is to store the following in header files:

  • Constants

  • Macros

  • System-wide global variables

  • Function prototypes

Then include that header file wherever needed.


Include Syntax

Both system and user header files use #include, but in different forms.

1. System Header Files

#include <file>
  • Searches for the file in standard system directories

  • You can add directories using the -I compiler option


2. User-Defined Header Files

#include "file"
  • Searches first in the current source file directory

  • Then in other include directories

  • You can add directories using the -I compiler option


Once-Only Headers (Header Guards)

If a header file is included more than once, the compiler may process it multiple times, causing errors.

To prevent this, use header guards:

#ifndef HEADER_FILE #define HEADER_FILE /* entire header file contents */ #endif

How It Works

  • The first time the file is included, HEADER_FILE is not defined, so the contents are included.

  • The macro is then defined.

  • If included again, the condition becomes false, and the file contents are skipped.

This technique is called a wrapper #ifndef or header guard.

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays