Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site brl-tgr.ARPA Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!think!harvard!seismo!brl-tgr!tgr!gwyn@BRL.ARPA From: gwyn@BRL.ARPA (VLD/VMB) Newsgroups: net.lang.c Subject: Re: 4.2 extern a DISASTER (Flame) Message-ID: <11600@brl-tgr.ARPA> Date: Mon, 15-Jul-85 16:37:48 EDT Article-I.D.: brl-tgr.11600 Posted: Mon Jul 15 16:37:48 1985 Date-Received: Thu, 18-Jul-85 02:47:50 EDT Sender: news@brl-tgr.ARPA Lines: 60 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 */ }