Compiling Mac Apps With ARC From Terminal

Matthew Campbell, January 17, 2012

The other day, I was looking around for a simple way to just compile a text file for a simple Mac app.  This isn’t something that you would do everyday but there are times when it’s nice to have the simplest bit of code out there without all the fuss involved with the XCode templates and everything else.

Write Objective-C Code Using Arc From Any Text Editor

So, check out this code I wrote just with a text editor (no XCode at all):

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]){
 	@autoreleasepool {
		NSString *helloString = @"Hello World";
		NSLog(@"%@", helloString);
	}
	return 0;
}

It’s pretty refreshing to actually see the entire program here and in just one place without any fussy extras attached. You can test many Objective-C Foundation procedures like this.

Note that we are going to use ARC to compile here and that is why I can use the @autorelease keyword. If you are not using ARC then you may need to use the older NSAutoreleasePool instead.

Compile Mac Code From Terminal With ARC Using Clang

You can use the command clang to compile the code above. XCode will do something similar for you in the background, but its nice to see the general format. Here is what you would type into Terminal to compile your Mac app:

clang -fobjc-arc -framework Foundation main.m -o maccommandlineapp

Here is what all this stuff means: clang is the compiler that you must use if you want ARC. -fobjc-arc lets the compiler know that we intend to use ARC for memory management. -framework Foundation is linking us to the Foundation framework so we can import that into our Mac code and use Objective-C classes. main.m is the code file that you are compiling and -o maccommandlineapp specifies the output file.

How To Use Your Compiled Mac Program

Make sure that you are in the folder where you located your code file and compiled your program. Then, simply type in open maccommandlineapp. You will see the output in the Terminal window.