How do a write portable programs?

Richard Harter g-rh at cca.CCA.COM
Sat Sep 10 14:52:33 AEST 1988


In article <1056 at nmtsun.nmt.edu> warner at hydrovax.nmt.edu (M. Warner Losh) writes:
>
>How do I write program that are easily protable when I HAVE TO use the
>system calls (be they setitimer() or lib$init_timer() or int21()...).  Is
>there a good and easy way that I can write my programs so that most of the
>code never has to be touched when I port?

Here are some practical suggestions which will simplify life for you if you
are writing portable code.  The most important thing is to isolate and segregate
the calls to system routines.  For example, suppose you want the date.  Now it
happens that the format of the date string returned from ctime is different
in different operating systems (Primos returns a 24 char string in the standard
Primos date format).  If you have calls to ctime scattered in your code you
will get an unpleasant little surprise the first time you try to port to Primos.[Experience speaks.]  If, however, you have your own date routine which calls
the system routines you only have one kludge to fix.  The rule is general --
wherever feasible go through an interface routine and only make the system
call once.  If this is not desirable attempt to isolate the system calls to
a handful of routines.

A second device is to create your own types for system arguments via define
statements in an include file which contains machine dependencies.  This 
protects you against various differences in argument types.

A particular case is the code for opening files (open and fopen both).
You will find that the arguments for these routines should be different
in PRIMOS and in VMS than they are in UNIX.  For example, suppose that you
want to open a stream file in append mode.  Here are the three statements
that you want:

UNIX	ptr = fopen(filename,"a");
VMS	ptr = fopen(filename,"a","rfm=var","rat=cr");
PRIMOS	ptr = fopen(filename,"wa");

Now you clearly do better if you have stashed away a define that looks

#ifdef VMS
#define APPEND_MODE "a","rfm=var","rat=cr"
#endif
#ifdef PRIMOS
#define APPEND_MODE "wa"
#endif
#ifdef UNIX
#define APPEND_MODE "a"
#endif

and open your stream files in append mode with the statement

	ptr = fopen(filename,APPEND_MODE);

-- 

In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
	Richard Harter, SMDS  Inc.



More information about the Comp.lang.c mailing list