What should NOT go in a header
What you'll learn: How to avoid "Multiple Definition" errors by keeping executable code and data out of your .h files.
Imagine a header file as a blueprint for a house. A blueprint tells the builder where the walls go and how big the rooms are, but the blueprint itself is not a house. You can hand a copy of that blueprint to ten different contractors, and they will all understand the design. However, you wouldn't try to store a physical brick inside the blueprint.
In C, header files are meant for declarations (blueprints), not definitions (the actual bricks).
The "One Definition Rule"
When you #include a header, the preprocessor literally copies the contents of that header into your .c file. If you put a variable or a function body inside a header, and then include that header in three different .c files, the compiler will try to create that variable or function three separate times. When it comes time to link your program together, the linker will get confused and shout: "Error: Multiple definition of 'x'!"
What to leave out
To keep your build process smooth, avoid putting these two things in your header files:
- Variable instances: Don't initialize variables like
int score = 0;. - Function bodies: Don't write the actual code (the
{ ... }part) for functions.
The Right Way vs. The Wrong Way
Here is what a header file should look like to avoid these common pitfalls.
/* graphics.h - THE WRONG WAY */
int screen_width = 800; // BAD: Allocates memory every time it's included
void draw_circle() { // BAD: The linker will see multiple draw_circle code blocks
/* code here */
}
/* graphics.h - THE RIGHT WAY */
extern int screen_width; // GOOD: Just a promise that this exists somewhere
void draw_circle(); // GOOD: Just a prototype (the blueprint)
By keeping the "bricks" (the actual memory and logic) in your .c files and only sharing the "blueprints" in your .h files, you ensure that every part of your program is looking at the same map without trying to build the same wall twice.
Key takeaway
Header files should only contain descriptions of what exists, never the actual data or logic itself.