In more detail:
Header files are simply copy-pasted to the point at which they are included by the preprocessor. So say your header file looks like this:
Code:
#ifndef INCLUSION_GUARD_H
#define INCLUSION_GUARD_H
int global_var;
#endif
If you include that header in multiple source files, the line "int global_var;" will appear multiple times. You'll be declaring the same global variable multiple times. Naturally, the linker gets confused when that happens.
What you need to do is define the global variable in one source file only, and declare in the other source files that it occurs elsewhere by saying
Code:
extern int global_var;
Of course, you could do just as I have said. But you'd have to type the "extern" declaration a lot, and there's an easier way: you can put the "extern" declaration right in the header file. C doesn't mind if you have code like this:
Code:
extern int global_var;
/* ... */
int global_var;
It's like having a function prototype and then a function definition. You can do that. So you can include the header file in the implementation file, the file that actually say "int global_var;", without any problems.
An example program:
header.c
Code:
#include <stdio.h>
#include "header.h"
int global_var;
void print_global_var(void) {
printf("%d\n", global_var);
}
header.h
Code:
#ifndef INCLUSION_GUARD_H
#define INCLUSION_GUARD_H
extern int global_var;
void print_global_var(void);
#endif
main.c
Code:
#include <stdio.h>
#include "header.h"
int main() {
global_var = 42;
print_global_var();
return 0;
}
[edit] Wow, three posts while I was typing this up. Well, it still seems to be relevant. [/edit]