I have a bit confusion about the variable definition and declaration using "extern" keyword. Assuming I want a variable 'timer' can be used in multiple c files. Then I can:
On c1.h
int timer;
Then on c1.c
#include "c1.h"
void timer_increase() {
timer++
}
Then on c2.c
#include "c1.h"
void print_timer() {
printf("%d", timer);
}
However, when I using extern variable:
On c1.h
extern int timer;
Then on c1.c
#include "c1.h"
int timer;
void timer_increase() {
timer++
}
Then on c2.c
#include "c1.h"
void print_timer() {
printf("%d", timer);
}
Both scripts work fine and I cannot see any reason that I have to used extern to declare a variable. Can anyone gives me any hints?
You have to define the variable once and declare it in header so that rest of the files have visibility to the variable.
When you don't use extern
in the header file, everytime you are defining the same variable in multiple files.