extern

Stephen Clamage steve at taumet.com
Sat Jun 30 01:20:52 AEST 1990


In article <910 at bjcong.bj.co.uk> emz at bjcong.bj.co.uk (ED ZIETARSKI) writes:
>In article <111254 at linus.mitre.org>, cookson at helios.mitre.org (Dean Cookson) writes:
>> I know that if you have an extern that is an array, you don't have to use
>> the size of the array in the extern declaration, you only need it in
>> the original declaration.  But is it an error to include it in the
>> extern declaration??
>> ...
>I would say it is an error because if you or someone else changes the array size
>at a later stage, (s)he would have to also know/remember that the external
>declaration needs changing.

Well, it may be a poor idea, but that is not the same thing as an error.
It is not an error.

The usual way to avoid the logistical problem of maintaining multiple
declarations is to put declarations needed by more than one file into a
header file and #include the header file where needed.  In a big program,
multiple such header files may be appropriate.

In this example, you would then have the declaration
	extern int foo[20];
in the header file.  A C program which strictly conforms to the ANSI C
standard must have a defining instance of this array as well as this
declaration.  Some C implementations require the separate defining instance
and some do not.

The usual trick is then to do something like this:

header.h:
	#ifndef EXTERN
	#define EXTERN extern
	#endif
	EXTERN int foo[20];
	EXTERN double bar;
	...

In all but the file containing main(), you simple #include header.h, and
in main.c:
	#define EXTERN
	#include "header.h"
	...

Now every file which includes header.h has an extern declaration for the
global identifiers, and main.c has defining instances for them.  This is
the most portable solution I know of, and strictly conforms to ANSI C.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list