What is the difference between Extern and global variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

What is the difference between Extern and global variables?

8th Oct 2020, 6:11 AM
Sneh Chauhan
Sneh Chauhan - avatar
11 Answers
+ 5
first of all understand external variable: Ex: file1.c ---------- #include stdio.h extern int a; int main() { printf("%d",a); return 0; } file2.c ---------- int a=5; whey ever we want to use a variable declared in one file into another file at that time we use extern keyword in above example variable 'a' is declared in file1 (here memory is not allocated for that variable it's only declared) in file2 value is defined to that variable.(memory is allocated) Global variable: with in the one file anywhere we can use it.
12th Oct 2020, 7:58 PM
Bhargava Ram
Bhargava Ram - avatar
+ 6
extern variables are only declared where as global variables are declared and defined.Both are visible through out the program
8th Oct 2020, 7:38 AM
Aditya rout
Aditya rout - avatar
+ 4
🎃#H P 22™🎃 Okay, so global variable can't be accessed in another module, right?
8th Oct 2020, 7:01 AM
Sneh Chauhan
Sneh Chauhan - avatar
+ 4
Aditya rout So, by program, you mean all the modules
8th Oct 2020, 7:39 AM
Sneh Chauhan
Sneh Chauhan - avatar
+ 3
I'm still not clear. If global variables can be accessed in any module then what's the use of extern variable
8th Oct 2020, 7:04 AM
Sneh Chauhan
Sneh Chauhan - avatar
+ 3
Bhargava Ram Got it finally 😌, thanks 😇... and yes suppose we defined a global variable before main () in file 1.c then can we use it in file2. c?? and is it necessary to include the file which contains the definition of extern int a;
12th Oct 2020, 9:02 PM
Sneh Chauhan
Sneh Chauhan - avatar
+ 2
Okkayy
8th Oct 2020, 7:08 AM
Sneh Chauhan
Sneh Chauhan - avatar
+ 2
Ya was also having the same doubt
9th Oct 2020, 10:59 AM
Nil Chouhan
Nil  Chouhan - avatar
+ 2
Sneh Chauhan suppose we defined a global variable before main () in file 1.c then can we use it in file2. c?? and is it necessary to include the file which contains the definition of extern int a; Not mandatory to use second file We can use extern variable in inside a file also, We can define that extern variable value in file1.c also file1.c ----------- #.............. Extern int a; int main() { printf("%d",a); fun1(); fun2(); } Void fun1() { printf("%d",a); } int a=5; } Void fun2() { printf("%d",a); } other difference is declaration and value assign is not possible at a time in extern variable. in global variable declaration and value assignment is possible at same time.
13th Oct 2020, 8:25 PM
Bhargava Ram
Bhargava Ram - avatar
+ 1
Yes,by program all modules.You have to declare extern variable before the main().
8th Oct 2020, 7:43 AM
Aditya rout
Aditya rout - avatar
- 1
I can't get it clear
11th Oct 2020, 11:17 AM
Offalinz US