Search code examples
cextern

Usage of extern variable in c files


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?


Solution

  • When you are declaring a variable inside the function, it is a local variable. It scope will be with in that function block. When you are using the extern key word it search for variable in the global section. So you have to declare the variable as a global variable.

    #include "header.h"
    int var = 4;
    void func2()
    {
       printf("I am function 2\n");
       return ;
    }
    

    Output will be ,

     I am function 2
     I am in function 1  var = 4