C Header Files
In this page:
Standard vs. Custom Header Files
Standard headers, included with angle brackets like #include <stdio.h>, are provided by the compiler's own library and searched for in its system include paths, whereas custom headers, included with double quotes like #include "utils.h", are your own files searched for relative to the current project first.
Example: Standard vs. Custom Header Files
#include <stdio.h>
int main() {
printf("stdio.h is a standard header");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Header Guards
A header guard wraps a header file's contents in #ifndef HEADER_NAME, #define HEADER_NAME, and a closing #endif, ensuring the preprocessor skips the file's contents entirely if it has already been included once in the current translation unit, preventing duplicate-definition compile errors.
Example: Header Guards
#ifndef MYHEADER_H
#define MYHEADER_H
#include <stdio.h>
int main() {
printf("Guarded against duplicate inclusion");
return 0;
}
#endif
Login to try C/C++/Java/PHP code in the editor
Declaring Functions in Headers
A header file should contain declarations — function prototypes, type definitions, macro constants — describing what exists, not the actual executable code that implements those functions; the implementations belong in a corresponding .c source file instead.
Example: Declaring Functions in Headers
#include <stdio.h>
int add(int a, int b);
int main() {
printf("%d", add(2, 3));
return 0;
}
int add(int a, int b) {
return a + b;
}
Login to try C/C++/Java/PHP code in the editor
Variables and Macros in Headers
Declaring shared constants and macros in a header lets every source file that includes it use the exact same values consistently, so changing a shared setting in one place (the header) automatically updates every file that depends on it, instead of hunting down scattered duplicate definitions.
Example: Variables and Macros in Headers
#include <stdio.h>
#define MAX_USERS 100
int main() {
printf("%d", MAX_USERS);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Preventing Duplicate Definitions
If a header contains an actual function body rather than just a prototype, and that header gets included into more than one .c file, the linker sees the same function defined twice and reports a duplicate-symbol error — which is exactly the failure header guards and declaration-only headers are designed to avoid.
Example: Preventing Duplicate Definitions
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d", square(4));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: