ANSI/Non-ANSI Function Declaration Macros

Peter Curran peter at isgtec.UUCP
Thu Dec 14 05:03:15 AEST 1989


This is a somewhat-modified re-post, due to technical difficulties.

In article <4603 at itivax.iti.org> scs at itivax.iti.org (Steve Simmons) writes:
>
>Currently I'm writing code that must compile with and without ANSI
>C features.  Ideally this could be done with no slgging the code
>with lots of #ifdef constructs like
>
>#ifdef __STDC__
>int	*foo( int const a )
>#else
>int	*foo( a )
>int	a ;
>#endif
>{
>	func body
>}
>
>While this works, it's got a weakness.  In having two separate declarations,
>one can over time let them get out of sync.  It's also a pain to write.
>Has anybody come up with a way of doing this so that I write the declarations
>once and once only?  Bizarre constructs considered within limits.
>-- 

I have solved this problem in two parts.

1.  Define a symbol PROTOTYPES as 1 if your current compiler supports
	prototypes, 0 otherwise.  (You could base this on the existence
	and/or value of __STDC__, but we have seen in the last while
	that this isn't too reliable.)

2.  Define a macro P(x) as follows

#if PROTOTYPES
#	define P(x)		x
#else
#	define P(x)		()
#	endif

3.  Now you can declare functions as, for example

		int foo		P((FILE *file, int abc));

	Note the double parentheses - they are important.  If PROTOTYPES
	is 1, this preprocesses to

		int foo (FILE *file, int abc):

	Otherwise it preprocesses to

		int foo ();

	This is obviously uglier than using a real compiler, but only
	three characters extra - a lot better than millions of #if's.

3.  Write function headers in the old style:

int foo (file, abc)
FILE *file;
int abc;....

	This is obsolescent, but all standard-conforming compilers are
	required to support it, and presumably will for the foreseeable
	future.  This means I get the benefits of prototypes whenever
	possible, but can port to obsolete compilers without too much
	pain.  Of course, once UNIX catches up with the rest of the
	world, I will abandoned the obsolescent form entirely.



More information about the Comp.lang.c mailing list