Reputation: 1576
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?
Upvotes: 0
Views: 201
Reputation: 4041
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
Upvotes: 2
Reputation: 17713
int var = 4;
<-- you have to move this out of func2()
.
As it stands (you declared it inside func2()
, it's only visible within that function.
To make it visible on other compilation unit (via extern
), you need to move it out to its file scope.
Upvotes: 1