简体   繁体   中英

what does it mean when there exist both declaration of variable and its extern declaration in the same file?

While I analyze some source codes, I found following definitions in one file(.c), not different file (This is one of the codes in a file produced by flex and there is no included file(stdio.h, string.h, errno.h, stdlib.h, inttypes.h) that defines yyin ):

extern FILE *yyin, *yyout;

FILE *yyin = (FILE*) 0, *yyout = (FILE *) 0;

I basically know what these statements mean.

But, extern keyword is used to make use of definitions such as variable, and function that live in another file. (It does not allocate memory for it.)

So, what I mean is that the code :

FILE *yyin = (FILE*) 0, *yyout = (FILE *) 0;

has to appear in another file, not in the same file.

For instance,

a.c

extern File *yyin;  /* It means that a.c want to use yyin declared in b.c */

int main(void) {
   yyin = *expressions*; /* yyin is variable in b.c */

   return 0;
}

b.c

File *yyin = (FILE*) 0;

Why do they exist in the same file? Are there any special meanings when extern keyword and normal variable declaration using same name live in the same file?

The first declaration is unusual in that it specifies extern explicitly, rather than relying on the default. Since the variables are declared in the file scope, they have external linkage by default, ie in your case the declaration is equivalent * to

FILE *yyin, *yyout;

Recall that each variable has a scope , storage duration , and linkage . Keyword extern specifies that a variable has external linkage; other options for linkage are static and no linkage.

Variables can have multiple declarations. As long as multiple declarations do not conflict with each other, C compiler can combine them.

In your case variables yyin and yyout have a declaration that says the variables have external linkage, and a definition that initializes both variables to NULL .

* The reason it is equivalent is that there are no other declarations of yyin and yyout . In general, a declaration without extern could become a definition if no other definition is provided in the same translation unit. This is called tentative definition . The declaration with extern does not become a tentative definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM