4.2 extern a DISASTER (Flame)

VLD/VMB gwyn at BRL.ARPA
Tue Jul 16 06:37:48 AEST 1985


Here is how to use external functions and data in C:

All data etc. may have its type DECLARED as often as necessary
to get correct code generated but must be DEFINED precisely
once.  In every DECLARATION of external data etc., use the
keyword "extern".  In the sole place that each datum etc. is
DEFINED (i.e., allocated storage if data, code if function),
omit the "extern" keyword.

If you do not specify an explicit initializer in the
DEFINITION (note that you cannot initialize a DECLARATION),
then external data is pre-initialized to zero (just what this
means has been subject to various interpretations; it is best
to explicitly initialize all extern storage except for that
that will always be stored into before being fetched).  An
external function that has never been DEFINED (by exhibiting
its source code instructions) will be flagged by the linker
as an unresolved global reference.

Of course, the standard C library provides several external
functions so that any references to them will be satisfied at
link time.

Some C compilers cheat a bit on the above rules; notably, most
UNIX C compilers allow multiple external definitions of the
same datum so long as not more than one of them explicitly
initializes the datum.  But you should not rely on this.

EXAMPLE:

Contents of file main.c:

	extern void sub();	/* may be in another file */
	extern int count;	/* ditto */

	main( argc, argv )
		int argc;
		char *argv[];
	{	/* definition of "main" starts here */
		count = 1;	/* stores into datum which
				   has storage allocated by
				   some other file	*/
		sub();		/* invokes function defined
				   elsewhere		*/
		return 0;
	}

Contents of file sub.c:

	int count /* = 0 */ ;	/* defines "count"; initialization
				   redundant in this case, since
				   0 is the default if not
				   specified */
	void sub()
	{	/* definition of "sub" starts here */
		(void)printf( "%d\n", count );
		/* because "printf" was not declared, it is
		   assumed to be an extern int function;
		   this is one of C's magic default rules */
	}



More information about the Comp.lang.c mailing list