Friday, December 4, 2009

Getting started with Objective-C and GNUstep on Linux

I couldn't find a simple one-stop guide by example, so here should be enough info to get you up and running with with Objective-C on Linux, including the obligatory hello world example. We will create a HelloWorld class, subclassed from the default object class, and show how to compile an example program.

Installation
This is specific to Arch, but you'll just need to install your distro's packages for gcc Objective-C support and the GNUstep base:

pacman -S gcc-objc gnustep-base

On Arch GNUstep installs to /opt/GNUstep.

Interface
We need to declare the interface for our class.

HelloWorld.h:

// use the GNUstep Foundation library
#import <Foundation/NSObject.h>

// declare interface for HelloWorld class as a subclass of NSObject
@interface HelloWorld : NSObject {

// instance variables
char *string;
}

// method definitions
- (id)setString: (char *)s;
- (char *)string;
- (void)speak;

// end interface declaration
@end


Implementation
Now to implement our simple class by writing the methods. Objective-C implementation files traditionally use the .m extension.


HelloWorld.m:

// include our interface declaration
#import <HelloWorld.h>

// start the implementation of the HelloWorld class
@implementation HelloWorld

// constructor
- (HelloWorld *)init
{
[super init]; // call init from superclass
[self setString: "hello world"]; // set default value
}

// accessor method to get value of string
- (char *)string
{
return(string);
}

// set string value
- (id)setString: (char *)s
{
string = s;
}

// print current value of string
- (void)speak
{
printf("%s\n", string);
}

// end the implementation
@end


Main
As with C, the entry point to our program is the main() function.

main.m

#import <HelloWorld.h>

int main (int argc, const char *argv[]) {

// create instance of our class
HelloWorld *hw = [[HelloWorld alloc] init];

// print the default
[hw speak];

// set new value and print
[hw setString: "goodbye"];
[hw speak];

// release memory
[hw release];

return 0;
}


Makefile
An example Makefile, showing required GNUstep libs. You will need to change the value of GNUSTEP to your distro's install location.

Makefile:

GNUSTEP=/opt/GNUstep
EXEC=hello
OBJS=HelloWorld.o main.o
LIBS=-lgnustep-base
LIBDIRS=-L${GNUSTEP}/Local/Library/Libraries
INCLUDES=-I${GNUSTEP}/Local/Library/Headers -I.

all: ${EXEC}

${EXEC}: ${OBJS}
gcc -o ${EXEC} ${OBJS} ${LIBDIRS} ${LIBS}

main.o: main.m
gcc -c ${INCLUDES} main.m

HelloWorld.o: HelloWorld.m HelloWorld.h
gcc -c ${INCLUDES} HelloWorld.m

clean:
rm -f ${OBJS} ${EXEC}


Compile and run

$ make
$ ./hello
hello world
goodbye


Further reading