Can we define a variable having extern storage class associated with it?

50 Views Asked by At

I was reading about extern storage class from this website:

https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

and there is this example:

#include "somefile.h" 
extern int var; 
int main(void) 
{ 
 var = 10; 
 return 0; 
}

Supposing that somefile.h has the definition of var

Since we cannot define the variable which is an extern storage class how is it working correctly?

Does it mean that if an extern variable is already defined somewhere in the script and then if I re-define it any further in my code it's going to work?

2

There are 2 best solutions below

0
On

C Language has methodology :- first Declare it and define it as you know daily use in C. You declare a function and define it somewhere downside.

The Main things is declaring a variable doesn't allocate memory. Memory is only allocated once you define it and in this case var is declare as well defined in somefile.h Memory is allocated via that file only and in this example extern states that this variable is defined somewhere else and Memory is already initialized for it. [blog]: https://errbits.com/2021/12/16/storage-classes-in-c/ "Storage Classes in C"

And while compile time compiler verify that for same ,if var is already defined in somefile.h it will compile without error since it will check its symbol table to verify if it there.

0
On

The keyword extern means external linkage. The below given example gives some basics about extern usage.

someclass.h

#pragma once
extern int var; //this DECLARES an GLOBAL int variable named var with EXTERNAL LINKAGE

In the above someclass.h, we have declared a global int variable named var with External linkage. This means we will be able to use this variable from other files.

someclass.cpp

#include "somefile.h"
int var = 10; //this DEFINES the GLOBAL int variable named var that was DECLARED inside somefile.h with external linkage

In the above file someclass.cpp we have defined the global variable named var that was declared in file somefile.h.

main.cpp

#include "somefile.h" 
#include <iostream>
int main(void) 
{ 
 std::cout<< var<<std::endl;  //prints 10
 return 0; 
}

In the above file main.cpp we've used(printed on console) the global variable named var without defining it in main.cpp. This is possible because the variable var as i said has external linkage.

The output of the program can be seen here.