files are included without causing conflicts
The Problem: Multiple Inclusion
The compiler only allows structures, functions or types to be defined once
The following three preprocessor directives avoid this redefinition problem:
- ifndef
- define
- endif
In large projects, it is very common for a main.c file to need to include both an A.h header and a B.h header.
If B.h also includes A.h, the compiler will end up seeing the contents of A.h twice.
If A.h contains the definition of a structure like your struct Node, the compiler will generate a fatal error.
Why are they necessary in a .h file?
Directives are necessary in the .h file because headers are designed to be included in multiple .c files, and potentially, to be included indirectly (one header includes another, which includes the first)
- .c Files Contain Implementation: The compiler processes each .c file in isolation
- .h files contain Declarations/Definitions:
- These files define the data types and function signatures that must be visible throughout the project
- By using Inclusion Guards, you ensure that this visibility is clean and unique at all times, maintaining code integrity
The compiler only allows structures, functions or types to be defined once.
- ifndef STRUCT_SELF_REFERENCING_H
- “If Not Defined”
- Condition: Checks if the unique symbol STRUCT_SELF_REFERENCING_H has NOT been defined yet
- define STRUCT_SELF_REFERENCING_H
- Definition: If the previous condition was true, define the symbol
- This ensures that the internal code is processed only once
- endif // STRUCT_SELF_REFERENCING_H
- Closes the conditional block started by #ifndef
First Inclusion: When a C file (e.g., main.c) includes STRUCT_SELF_REFERENCING_H for the first time, the #ifndef directive is true (the symbol does not exist).
The preprocessor goes to the next line, defines the symbol with #define, and then processes the code in the structure.
Second Inclusion: If later, another header included by main.c tries to include STRUCT_SELF_REFERENCING_H a second time, the #ifndef directive will be false (because the symbol was already defined in step 1).
Result: The preprocessor skips all code up to #endif, preventing the structure definition from reaching the compiler twice.