Objective-C through a preprocessor
Question
Can Objective-C be implemented by translating it into C?
Answer
The concise answer is yes, in fact contemporary Objective-C
implementations, as provided by for instance Stepstone and BPG,
actually translate Objective-C to C which in turn is processed by
the C compiler already present on the system.
However, one must not forget that (most of) the power of Objective-C
is provided by the Objective-C runtime library, which has nothing to
do with the Objective-C compiler other than that the compiler
generates code which calls the library.
A program translating Objective-C to C needs to perform the
following actions:
- Translate instance variable declarations in a class interface into a
structure definition. Each generated structure describes
all instance variables of the class' instances.
- Translate every method implementation into a function with exactly the
same arguments as the method, plus the implicit first two arguments
self
and _cmd
. Within the method, all
references to an instance variable ivar
translate to
self->ivar
.
- Translate every method invocation into a lookup of the function
implementing the method for this object, followed by an invocation
of that function. (On NeXT's runtime, both the lookup and
invocation are performed by a single function).
- For every message sent to a named class, like
alloc
in
[[MyClass alloc] init]
, invoke a runtime library
function to obtain the class object to which the factory message can
be sent.
- For every object file created, build the data structures used by the
runtime for every class implementation and protocol declaration.
Also output a constructor function to have the runtime library add
the information in this object file to its data structures.
- All Objective-C specific warnings and errors must be generated by the
translator, since obviously the C compiler has no notion of
Objective-C concepts.
An existing, available Objective-C Translator is OCT
though a quick glance shows it seems both rather Amiga oriented and
old (i.e. there is no ./configure
, me spoiled
brat).
Question by mitzel@ionet.net. Answer
based on remarks by
Gregory H. Anderson,
Jeremy Bettis,
Don Yacktman,
Christopher Rath and
Bill Bereza.
Mail your comments on this page to tiggr@ics.ele.tue.nl.
Up: Infrequently Asked Questions concerning
Objective-C
Next: Reference counting in FoundationKit
Copyright (C) 1995, 1996 Pieter J. Schoenmakers. All rights reserved.
tiggr@ics.ele.tue.nl