Reputation: 376
Can I compile an Objective-C program to C?
I'm interested if this can be done so that it can be compiled with other C compilers.
I am aware that GCC can compile Objective-C.
Upvotes: 2
Views: 1610
Reputation: 365577
Sure. For example, POC compiles Objective C to plain C code, and the recommended way to use it is to then compile that C code with gcc.
Of course the generated C is an unreadable mess, consisting mostly of calls (through generated extern
declarations) to objc_runtime calls, so you'll need to link that runtime to your compiled code.
There's also an LLVM backend that generates C code from any frontend. So, you can plug in the clang
Objective C frontend and the C backend and build your own ObjC-to-C compiler. The result will probably be even more unreadable than what POC generates.
Of course most people don't want to compile Objective C*, they want to compile "Objective C 4.0".** POC won't do that; only clang and llvm-gcc will (and in the future, most likely only clang). And they don't just want an Objective C runtime, they want the OS X or the iOS runtime, or at least OpenStep, which again pretty much means clang, llvm-gcc, or gcc.
The big question is, why do you want to do this? You will need to have an Objective C runtime to link to, and your C code will have to be compiled in a way that's ABI-compatible with the way that runtime was compiled, so… I'm not sure what you're going to gain over just compiling from ObjC to native code with gcc or clang in the first place.
* As in the language defined in Brad Cox's 1986 book and/or in his 1991 followup.
** Note that Apple explicitly decided not to call their latest revisions to the language "Objective-C 4.0"… or anything else. The last version with a name, or a real specification, was "The Objective-C 2.0 Programming Language". But Apple has continued to add features, and the "unnamed feature set that came in with the LLVM 4.0 frontend for Objective-C 2.0" is a bit of a mouthful.
Upvotes: 12
Reputation: 100602
Technically, yes, but it'll be really ugly. LLVM had a C backend — i.e. it could compile to C — up to version 3.1. There have been efforts to revive it but I can't speak as to their progress. There's also a C++ backend that is better maintained but doesn't quite do the same thing.
However you'll have the obvious problem that none of the Foundation libraries will be available on your target platform. No NSString
, no NSArray
, etc. Once you've found a working implementation of those you'll also have found a working Objective-C compiler.
Upvotes: 2