panku said:
what is diff the declaration and definition?
void main()
Make that
int main( void )
since main() is supposed to return an int.
{
extern int i;
i=90; //Error: i is undefined
}
as extern int i is there it is giving error and also when we write
extern int i=90 then also it gives error ? why???????????????????????
What you have with
extern int i;
isn't a defininition but just a declaration. With a decla-
ration you merely tell the compiler that something (an ob-
ject or a function) exists somewhere and that it shouldn't
worry about that it doesn't know where that thing actually
is. So, in plain words, it says: "Somewhere but not here
an int variable named 'i' is defined and I would like you
to use that when I write 'i' in the current context."
But to get that to work you must also supply a definition of
what you promised the compiler to exist. Otherwise the linker
will catch up with you and tell you that it's not defined (via
the dreaded "undefined reference" linker error message). One
way to do so would be to change your program to
int main( void ) {
extern int i;
i = 90;
return 0;
}
int i;
Now you have the required definition of 'i' in the last
line - it makes the compiler create an object of type int
and name 'i' that the merely declared 'i' in main() can
be associated with. Another way would be to have 'i' de-
fined in another source file and then link them together.
It's rather similar to function declarations: you proba-
bly wouldn't be too surprised if the linker complained
about
extern int foo( double );
int main( void ) {
foo( 3.14 );
return 0;
}
Here you also just tell the compiler that some function
foo() exists somewhere else but there's no definition that
would tell what foo() is actually doing. Obviously, without
that the program can't be created and you get a linker error
about an undefined reference to 'foo'. (Note that the 'extern'
qualifier is redundant for function declarations, so you will
not see it used that often with function declarations.)
Another point: since
external int i;
does not define a variable but merely declares it you also
can't initialize it. Initialization can only happen at the
place where something is defined. Consider what should hap-
pen if it would be possible and you would do
int main( void ) {
extern int i = 90;
return 0;
}
int i = -42;
You'd have two contradictory initializations for the same
variable! What should the poor compiler do with that?
But when you instead have
int main( void ) {
extern int i;
i = 90;
return 0;
}
int i = -42;
things are fine again - 'i' will be initialized to -42
while it's created and then later in main() its value
gets changed to 90.
Regards, Jens