home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ogicse!decwrl!world!ksr!jfw
- From: jfw@ksr.com (John F. Woods)
- Newsgroups: comp.lang.c
- Subject: Re: Summary: Why use "extern" on function prototypes.
- Message-ID: <14004@ksr.com>
- Date: 21 Jul 92 15:58:50 GMT
- Article-I.D.: ksr.14004
- References: <12271@anderson> <1992Jul21.070641.13516@dcs.qmw.ac.uk>
- Sender: news@ksr.com
- Lines: 62
-
- Since I'm following up a followup, and not sure of the attributions anymore,
- I'm just going to shear them off.
-
- >> I checked in 'C the Complete Reference' by the C god himself, H.Schildt.
- >> He says that extern variables (and functions) are not allocated in that
- >> section of the program. Thus, I think extern, although not necessary in
- >> headers, is used to reduce memory considerations.
-
- Oh worshipper of false deities! Had you read "The C Programming Language"
- by Kernighan and Ritchie, you would have learned that there are two kinds
- of ways of referring to external variables, _declarations_ and _definitions_.
- Declarations announce the properties of a variable; definitions also cause
- storage to be set aside. The (file scope) declaration
-
- int i;
-
- is called a "tentative definition"; if no definition with an initializer
- is seen later, it will define the variable i with an initial value of 0;
- otherwise, it will act the same as
-
- extern int i;
-
- which is a declaration referring to some other definition. There most be
- no more than one definition of an identifier; multiple definitions of the
- same identifier in a program does not result in extra copies of the variables,
- it is an *error*. It is for this reason that object declarations in header
- files should contain the word "extern".
-
- For functions, the situation is slightly different (but still the same). This
- is a *definition* of a function:
-
- void foo() {
- /* ok, so it isn't a very interesting function. */
- }
-
- This is a *declaration*:
-
- extern void foo();
-
- But this is ALSO a declaration:
-
- void foo();
-
- because there is no function body. Function declarations do not *need* the
- keyword extern to indicate that they are declarations.
-
- Now, there is one extra subtlety to the above (which, by the way, the Standard
- (rather, the Rationale thereto) calls the "Strict Ref/Def Model". Many
- historical C implementations (in particular, the one written by Messrs. K&R)
- use the "Relaxed Ref/Def Model", in which tentative definitions remain
- tentative until link time; so, while the Standard considers
-
- file1.c file2.c
- int i; int i;
- foo() { bar() {
- i = 1; i = 2;
- } }
-
- to erroneously define "i" twice, the Relaxed Ref/Def model used by UNIX will
- fold *all* tentative definitions in multiple translation units into one
- tentative definition. In this model, it is acceptable for header files not
- to use extern to declare external data objects.
-