Re: Use of 'extern' keyword
- From: "Antonio Contreras" <anconor@xxxxxxxxx>
- Date: 28 Jul 2005 03:48:24 -0700
siliconwafer wrote:
> Hi all,
> I wanted to know that is use of extern keyword mandatory in case of
> global variables and functions used in other source files?
> i.e consider a following piece of code from MSDN explaining extern
> storage class:
> /******************************************************************
> SOURCE FILE ONE
> *******************************************************************/
>
> extern int i; /* Reference to i, defined below */
> void next( void ); /* Function prototype */
>
> void main()
> {
> i++;
> printf( "%d\n", i ); /* i equals 4 */
> next();
> }
>
> int i = 3; /* Definition of i */
>
> void next( void )
> {
> i++;
> printf( "%d\n", i ); /* i equals 5 */
> other();
> }
>
> /******************************************************************
> SOURCE FILE TWO
> *******************************************************************/
>
> extern int i; /* Reference to i in */
> /* first source file */
> void other( void )
> {
> i++;
> printf( "%d\n", i ); /* i equals 6 */
> }
>
>
> Here,if I drop the extern keyword from source file 2 and compile and
> link the 2 source files I get the same result as with 'extern' keyword.
> i.e extern keyword is optional.
IIRC any declaration at file scope without an intialization is
considered to be a tentative declaration. This means that if the
compiler encounters the same variable declared more than once it fuses
all the ocurrences into a single global variable. In the case of gcc
you can force this situation to issue a warning. However, if you insist
in using global variables, it's much better practice to define the
variable just once and include it in a header file with the extern
keyword that can be conviniently included in other files as needed.
> same is the case with functions.
A function that has no storage class specifier is considered to have
extern class, so they're visible in all compilation units unless
they're explicitly declared to be static, in wich case they're only
visible in the file they're declared.
> If so in which cases is the use of 'extern' mandatory?
If you want some global variable defined in another file to be visible
just inside a function (or a block) then you need the extern keyword,
otherwise the declaration would be considered to be a local variable.
Ie:
File a.c:
int a = 0;
File b.c:
void func (void) {
extern int a;
....
}
HTH.
.
- Follow-Ups:
- Re: Use of 'extern' keyword
- From: Jack Klein
- Re: Use of 'extern' keyword
- References:
- Use of 'extern' keyword
- From: siliconwafer
- Use of 'extern' keyword
- Prev by Date: Re: Should function argument be changed in function body?
- Next by Date: Re: malloc modifying a passed string
- Previous by thread: Use of 'extern' keyword
- Next by thread: Re: Use of 'extern' keyword
- Index(es):
Relevant Pages
|