596 views
0 votes
0 votes

suppose i have 2 files

//FILE1.h

int var = 10;

 

//FILE2.c

#include<stdio.h>
#include "FILE1.h"

int main()
{
    
    printf("%d",var);
    
}

so this file2.c gives output “10” so why we use “extern” keyword cause without using it our work that is access the variable from other file is easily done without “extern” so what is exact use of extern keyword.

thank you

1 Answer

Best answer
1 votes
1 votes
extern is used to refer to variables from different compilation units – not necessarily a file but typically a file. By including one file in another you are currently having a single compilation unit. Compile the two files separately using “gcc -c ” and link them using “gcc” into a single executable. You can see the use of “extern”.
selected by

Related questions

0 votes
0 votes
2 answers
1
ykrishnay asked May 30, 2022
988 views
int main(){extern int a = 20;printf("%d",a); }//why this gives error but followig code is not extern int a =20;int main(){printf("%d",a); } //why this happens that first ...
2 votes
2 votes
1 answer
2
rahul sharma 5 asked Nov 23, 2017
1,032 views
#include <stdio.h int main() { int a=10; extern int a; return 0;} Why this gives compilation error? Extern is just a declaration.So why it is giving error on c...
2 votes
2 votes
2 answers
4
Rohan Mundhey asked Nov 5, 2016
3,545 views