Odd question re: extern vs. static

Steve Summit scs at adam.pika.mit.edu
Fri Jul 21 16:03:16 AEST 1989


The following fragment looks illegal, and probably is:

	extern int f();
	static int f;

You might well ask why anyone would write such a thing, and the
answer is, if the extern function declaration comes from a header
file:

	#include "f.h"		/* happens to contain extern int f(); */
	static int f;

(this has happened to me twice now; it is not a hypothetical
situation.)

Marking a file-scope symbol "static" is supposed to make it
private; to protect it from interfering with global variables in
other source files.  The problem here is essentially that a
symbol from another source file is interfering with the local,
static symbol.

This problem comes up more frequently now that function prototype
use essentially requires all global functions to have
extern declarations in header files.

It wouldn't surprise me at all if this sort of code is explicitly
illegal.  I know why compilers reject it -- they have one
per-source-file global symbol table, "f" goes into it when the
extern function declaration is seen, and the later static
variable declaration is simply incompatible, since there is no
notion of "let a static declaration override an external one."

I guess my question is, has anyone ever considered adding such a
notion to a compiler?  I agree it would be a wart, but the issue
is more than an academic one -- I like to think that by declaring
file-scope symbols "static" I'm protecting myself from name
clashes, but I still essentially have to worry about every
symbol declared by every other module's header files I #include.

Actually, thinking about it one way, it's not such a wart -- it's
similar in spirit (though certainly not in implementation) to the
way most, if not all (did you get an answer, Andrew?) compilers/
linkers essentially ignore an

	extern int f();

if f is never called.

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.lang.c mailing list