Avoid multiple inclusion of header file

Generally, a header (.h) file should have (A header file need not have a .h extension, its just a convention):

1. Macro definitions (preprocessor #defines).
2. Structure, union, and enumeration declarations.
3. Any typedef declarations.
4. External function declarations.
5. Global variable declarations.

Put declarations / definitions in header files if they will be shared between several other files. If some of the definitions / declarations should be kept private to some .c file, don;t add it to the header files.

How does one prevent a header file from included twice?. Including header files twice can lead to multiple-definition errors.

There are two methods to prevent a header file from included twice

#ifndef HEADER_FILE
#define HEADER_FILE
…header file contents…
#endif

A line like
#pragma once

inside a header file is an extension implemented by some preprocessors to help make header files idempotent (to prevent a header file from included twice).

What happens if you include unwanted headers?
You will end up increasing the size of your executables!

Leave a Reply

Your email address will not be published. Required fields are marked *