856 views
1 votes
1 votes
why is it showing error??
#include <stdio.h>

int main() {
  extern int i;
  i=20;
  printf("%d",i);
}

2 Answers

Best answer
2 votes
2 votes

extern int i;

means somewhere else there is a definition of the variable i, and that somewhere else may be in the same source file or some other source file. Extern keyword before a variable does not requires that the variable must be defined in some other source file. It is fine to define in the same file. Extern keyword means just declaration (but no definition). The linker will find the needed definition from other place in the linking phase if actually there exist a definition somewhere else.

This is one of the way to link:

// header.c
int x,y,z;
//mainprog.c
#include <stdio.h>
int main() {
	extern x,y,z;
	x = 10;y = 20;
	z = x+y;
	printf("%d\n",z);
}

compile :

 $> gcc header.c -o header.o -c
 $> gcc mainprog.c -o mainprog.o -c

Now two object files are generated , we need to link them :

$> gcc -o finalprog header.o mainprog.o

// run the executable finalprog
./finalprog

Output:

30
selected by
2 votes
2 votes
extern int i ;

doesn't allocate any memory for variable i

variable is assumed to be available somewhere else and the resolving is deferred to the linker.

Therefore compiler will raise undefined reference to i as error and the program will not be executed

Related questions

0 votes
0 votes
1 answer
1
radha gogia asked Aug 10, 2015
392 views
CASE A: CASE A: &#8234;#&lrm;include&#8236;<stdio.h int divide( int a, b) { return 7; } int main() { int a=divide(8,3); printf("%d",a); return 0; }CASE B :CASE B : #inclu...
0 votes
0 votes
1 answer
2
0 votes
0 votes
0 answers
3
`JEET asked Dec 8, 2018
275 views
#include <stdio.h int atoi(char s[]) { int i, n; n = 0; for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i) n = 10*n + (s[i] - '0'); return n; } int main() { char s[] = "jitendra...
0 votes
0 votes
4 answers
4
Sanjay Sharma asked Jun 7, 2016
1,909 views
If a= 10 then what will be the value of b in a C language code.If b= a++ + a++ + a++;.30.23.33.Undefined behaviour