蓝天,小湖,湖水中一方小筑

Compile Object-C program in command line

Recently I am working on an iOS project, and I am getting interested in the language itself. But it is inconvenient to start Xcode for each program, especially for program without UI elements in. So I want to set up a command line environment that can compile and execute ObjC program.

Prepare the code

First I have to prepare the ObjC file. I have created one file called helloworld.m in current directory, and here is the content:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSLog (@"Hello World!");

    [pool drain];
    return 0;
}

Okay, the program does the same thing as the first program of other languages do: print out Hello World! string.

Compile and execute the program

Mac OS

I have installed Xcode before, so I don’t know whether those commands can be run successfully without Xcode command line tools.

There are two methods to compile ObjC program from command line in Mac OS, one is using gcc and the other one is using clang. Both commands below can generate ObjC executable file.

clang -framework Foundation helloworld.m -o helloworld_clang

gcc -framework Foundation helloworld.m -o helloworld_gcc

On my side, the two binary file has the same size, and the execute results are the same except the timestamp:

$ ./helloworld_clang
2013-01-24 01:56:27.009 helloworld_clang[7845:707] Hello World!

$ ./helloworld_gcc
2013-01-24 01:56:29.744 helloworld_gcc[7846:707] Hello World!

Linux

With GCC, the command line compilation can also be done on Linux platform. I am using Debian and have set up the environment after refering [this post](http://stpetrus27.wordpress.com/2011/06/20/compile-objective-c-programs- on-linux/). Here are the brief steps:

First Install those packages first to prepare the environment.

sudo apt-get install gobjc gnustep gnustep-devel

Then compile the program with command listed below:

gcc `gnustep-config --objc-flags` helloworld.m -o helloworld_gcc `gnustep-config --objc-libs` -lgnustep-base

After the command return, you can find binary file helloworld_gcc in the same directory.

So, with this feature, some simple program can be executed without running Xcode, a little convenient for language learning for me.