extern int i;
means somewhere else there is a definition of the variable i, and that somewhere else may be in the same source file or some other source file. Extern keyword before a variable does not requires that the variable must be defined in some other source file. It is fine to define in the same file. Extern keyword means just declaration (but no definition). The linker will find the needed definition from other place in the linking phase if actually there exist a definition somewhere else.
This is one of the way to link:
// header.c
int x,y,z;
//mainprog.c
#include <stdio.h>
int main() {
extern x,y,z;
x = 10;y = 20;
z = x+y;
printf("%d\n",z);
}
compile :
$> gcc header.c -o header.o -c
$> gcc mainprog.c -o mainprog.o -c
Now two object files are generated , we need to link them :
$> gcc -o finalprog header.o mainprog.o
// run the executable finalprog
./finalprog
Output:
30