I am trying to build a simple test case for extern variables using 4 files. The files are as follows
//header.h
#include <stdio.h>
void func1();
void func2();
extern int var;
//main.c
#include "header.h"
int main()
{
func2();
func1();
return 0;
}
//func1.c
#include "header.h"
void func1()
{
printf("I am in function 1\t var = %d", var);
return ;
}
//func2.c
#include "header.h"
void func2()
{
int var = 4;
printf("I am function 2\n");
return ;
}
I am trying to understand the concept of an extern variable. I compiled these files as
gcc -c main.c
gcc -c func1.c
gcc -c func2.c
and linked them together as
gcc -o main main.o func1.o func2.o
I got an error saying
func1.o: In function `func1':
func1.c:(.text+0x6): undefined reference to `var'
Why is that? I defined it in func2 and then use it in another file. What is wrong with my understanding?