Correct or Not or Old-fashioned or Bug

Geoffrey Rogers grogers at convex.com
Wed May 22 01:07:35 AEST 1991


In article <ZHOUMI.91May20182038 at marlboro.nff.ncl.omron.co.jp> zhoumi at nff.ncl.omron.co.jp (Zhou Mi) writes:
>
>When I am working in a project, I find that someone in my group write
>the following program. Though it seems work well, I still wonder if it
>is correct or better ??
>
>-----file 1 (named pro_all.h) ---------
>	int i;
>
>------file 2 (named pro_main.c) --------
>	#include "pro_all.h"
>	
>	void main()
>	{
>		sub1();
>		sub2();
>		sub3();
>	}
>	
>--------- file 3 (named pro_sub1.c) --------
>	#include "pro_all.h"
>	void sub1()
>	{
>		i = 1;
>	}
>

In non-ANSI C compiler/loader environments this may or may not work. You
could get multiple defined symbols for i, depending upon the model that the
compiler used for external variables.

The above code in not ANSI conforming, because you do have multiple
definitions of i.

One of the ways that I got around this problem of only having one file
with all of my externals is to do the following:

-------------- file 1 (pro_all.h) ----------------------
#ifndef EXTERN
#define EXTERN	extern
#endif

EXTERN int i;

------------- file 2 (pro_main.c) ----------------------
#define EXTERN

#include "pro_all.h"

void main()
{
	sub1();
	sub2();
	sub3();
}

--------- file 3 (pro_sub1.c) --------
#include "pro_all.h"
void sub1()
{
	i = 1;
}

This way when pro_all.h is included in the main all the externals get
defined and when it gets included in other files they get declared.

+------------------------------------+---------------------------------+
| Geoffrey C. Rogers   		     | "Whose brain did you get?"      |
| grogers at convex.com                 | "Abbie Normal!"                 |
| {sun,uunet,uiucdcs}!convex!grogers |                                 |
+------------------------------------+---------------------------------+



More information about the Comp.lang.c mailing list