Portability enhancing C extension - (nf)

notes at ucbcad.UUCP notes at ucbcad.UUCP
Sun Oct 2 11:56:04 AEST 1983


#R:watmath:-587000:ucbesvax:4800025:000:2310
ucbesvax!turner    Oct  1 18:00:00 1983

I, like, totally grok what you mean.  The problem of C not knowing (or
much caring) about types of arguments of external functions is not
completely alleviated by lint, since, to be fully useful, we would
also want to have pointers to functions, with argument-types checked.
(lint can't do this, in general, so it doesn't do it at all.)

I have an interesting little hack, which works for my situation.  I am
charged with defining and maintaining (not mention implementing), a
special-purpose database.  To provide a security blanket, I define all
entry-points in a global #include file as macros, where the *real* names
of access routines are all icked-out with underscores.  This takes care
of *numbers* of arguments (since cpp complains of argument mismatches).

But what about the *types* of arguments?  My people here don't use lint
(and their code shows it!), so giving them a lint library is no help.
After a bit of C-puzzling, I came up with the following ultra-cutesy-
but-probably-portable macro:

    #define _declare_(Expr,Type) ( sizeof((Expr) == (Type) 0), (Expr) )

	/* Example: */
    extern SomeStruct *_Icky_Real_Name_( );

    #define FakeName(arg1,arg2) \
		_Icky_Real_Name_( _declare_(arg1,char *), \
				  _declare_(arg2,SomeStruct) )

Now, calls through FakeName must have exactly two arguments, one (char *),
the next of type SomeStruct, if they are to compile without errors.

Exegesis of "_declare_":

	"( sizeof(...), (Expr) )" = (Expr), loosely speaking; sizeof(...)
	is a constant, and the code generator throws it out, since a
	constant can't have side-effects.  The comma operator was a
	good idea.

	Also, sizeof(...) suppresses any code generation for (...).
	Thus we circumvent a problem with macros: that multiple mentions
	of a formal parameter involve multiple evaluations of the actual
	parameter--bad craziness, but we get around it here.

	Finally, "(Expr) == (Type) 0" will generate an error message,
	if the type of Expr is incomparable with something of type Type.

But, given a choice, I would rather exercise my remaining inventive powers
in ways other than hacking around holes in C.  Especially considering that
my inventive powers are out to lunch a lot, these days.

    No Strong-Typing vs. Weak-Typing Jihads, Please,
	Michael Turner (ucbvax!ucbesvax.turner)



More information about the Comp.lang.c mailing list