A header is just a C source file that generally only contains:
- Preprocessor
#define
s
- Type declarations
- Function declarations
- Comments :)
There's nothing magical to it.
This could be a fully valid entire header:
// Save this as "adding.h"
int add_numbers(int a, int b);
It would be used like this:
In the file main.c
:
#include "adding.h"
int main(void)
{
const int x = 12;
const int y = 27;
printf("the sum of %d and %d is %d\n", x, y, add_numbers(x, y));
return 0;
}
Then you'd of course also have adding.c
:
#include "adding.h"
int add_numbers(int a, int b)
{
return a + b;
}
--
Sometimes, in real projects, headers #include
other headers, and that can create problems with repeated definitions (and also costs compilation time). To protect against that, include guards are often added. It would look like this:
// In "adding.h".
#if !defined ADDING_H_
#define ADDING_H_
int add_numbers(int a, int b);
#endif // ADDING_H_
The contents of the header is just wrapped in an #if defined
block, with a #define
of the checked-for symbol inside it. This makes sure that multiple inclusions during the compilation of a single C file are harmless.