17 August 2011

Step-by-step running Objective-c on Ubuntu Linux for Windows users

SA,

In this post, I'll try to compile and run the code in this Objective-c Wikibook lesson

If you are using M$ Windows, go download VMWare Player from here and then download ubuntu Linux, I am using version 10.04.. you can get some recent version if you like..

There are variety of tutorials online to help you install ubuntu on vmware.. it is a very trivial task..


Once you have your ubuntu distribution up and running (either a VM or a standalone installation)... keep reading ...

Ubuntu linux (and almost all linux distro) come with Parts of GCC (GNU Compiler Collections) pre-installed.

Let's test the existence of a C compiler. Now type in the command line the following command:

cat <<EOF>hello.c
#include<stdio.h>
int main(void){printf("In the name of Allah\n");}
EOF

And Then:
gcc -o hello hello.c && ./hello


If you find the following output printed on the console window, then we are going in the right direction:
In the name of Allah



Now let's install the Objective-c compiler into the GCC (it is about 4MB):
Open synaptic (from command line `sudo synaptic` [will prompted for your password]

Now search for "objc" in synaptic.. and then install the package "libobjc2".


Now we are ready...

Let's try to compile and run the example in the wikibooks link we have talked about before..

First create a directory in your home directory called "objc"
and then put the three files below in it

Here's the interface Point:

//Point.h
#import <objc/Object.h>

@interface Point : Object
{
@private
    double x;
    double y;
}

-(id) x: (double) x_value;
-(double) x;
-(id) y: (double) y_value;
-(double) y;
-(double) magnitude;

@end


(note, return to the wikibooks link if you need to understand the code)

And here's the implementation class:

//Point.m
#import "Point.h"
#import <math.h>

@implementation Point
    -(id) x: (double) x_value
    {
        x = x_value;
        return self;
    }

    -(double) x
    {
        return x;
    }

    -(id) y: (double) y_value
    {
        y = y_value;
        return self;
    }

    -(double) y
    {
        return y;
    }

    -(double) magnitude
    {
        return sqrt(x*x + y*y);
    }

@end

And now the Test file:


//Test.m
#import "Point.h"
#import <stdio.h>

int main(void)
{

    Point *p = [[Point alloc] init];
    [p x:10.0];
    [p y:20.0];
    printf("The Distance from Point %g to %g is %g\n", [p x], [p y], [p magnitude]);
    return 0;
}

Now let's compile the above program..
The easiest way to do so is to execute the following command from the same directory where these files exist (objc directory)

gcc -o Test *.m -lobjc -lm

Note, the `-lm` is required only because we use the math.h library.
now let's execute the program:
./Test 
The Distance from Point 10 to 20 is 22.3607


That's all.. hope that you find this post helpful..

1 comment:

Anonymous said...

Thanks for Nice Posting..!