From this really long answer:
Using extern
is only of relevance when the program you're building
consists of multiple source files linked together, where some of the
variables defined, for example, in source file file1.c
need to be
referenced in other source files, such as file2.c
.
Best way to declare and define global variables
Although there are other ways of doing it, the clean, reliable way to
declare and define global variables is to use a header file file3.h
to
contain an extern
declaration of the variable. The header is included
by the one source file that defines the variable and by all the source
files that reference the variable. For each program, one source file
(and only one source file) defines the variable. Similarly, one header
file (and only one header file) should declare the variable.
file3.h
extern int global_variable; /* Declaration of the variable */
file1.c
#include "file3.h" /* Declaration made available here */
/* Variable defined here */
int increment(void)
{
return global_variable++;
}
file2.c
#include "file3.h"
#include <stdio.h>
void use_it(void)
{
printf("Global variable: %d\n", global_variable++);
}
The next two files complete the source for prog1:
prog1.h
extern void use_it(void);
extern int increment(void);
prog1.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
int main(void)
{
use_it();
global_variable += 19;
use_it();
printf("Increment: %d\n", increment());
return 0;
}
prog1
uses prog1.c
, file1.c
, file2.c
, file3.h
and prog1.h
.