Pages

Categories

Compiling Objective-C without XCode in OS X

Ok, so I’m about to blog about something which may seem blindingly obvious to OS X developers, but to be fair I didn’t find much on Google myself.

I’m new to Objective-C and programming for OS X in general, but I get frustrated when all articles, books and tutorials narrow themselves down to just one IDE and push you away from the glory of the command line. So how do you compile a simple “Hello World!” application in objective-C on a Mac?

This is a brief “Hello World!” tutorial for ObjC, on top of demonstrating the build process beyond XCode.

We’ll create a class called “Talker” which simply says things we tell it to, then we’ll run it from our main() function.

Create your directory structure

Simple enough. Make yourself a directory called “HelloWorld” or something like that, then create a sub-directory called “build”.

mkdir HelloWorld
mkdir HelloWorld/build

Create the interface and implementation files

HelloWorld/Talker.h

#import <Foundation/Foundation.h>

@interface Talker : NSObject

- (void) say: (STR) phrase;

@end

HelloWorld/Talker.m

#import "Talker.h"

@implementation Talker

- (void) say: (STR) phrase {
  printf("%s\n", phrase);
}

@end

Create your main() file

HelloWorld/hello.m

#import "Talker.h"

int main(void) {
  Talker *talker = [[Talker alloc] init];
  [talker say: "Hello World!"];
  [talker release];
}

Compile it with gcc specifying -framework Foundation

gcc -o build/hello Talker.m hello.m -framework Foundation

Run it!

./build/hello

Hello World!

Enjoy :)

WordPress appears to have removed some formatting whitespace from my code, but it will still compile.

This entry was posted on Friday, June 27th, 2008 at 8:33 am and is filed under Objective-C. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No Responses to “Compiling Objective-C without XCode in OS X”

No comments yet

Leave a Reply







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>