Wednesday, May 5, 2010

First program in Objective-C in Windows Vista

The main purpose of this post is to write a simple Objective-C program in Windows Vista. Initially, to setup the environment for compiling Objective-C, download GNUStep System and GNUStep Core from GNUStep website. Install the GNUstep System then install the GNUStep Core. This order of install is very important. Now to make sure that you properly install the previous two components. Go to the installed GNUstep directory. There must be a file named 'msys.bat'. If you try to open this file then following window will pop up and it will setup the GNUStep environment.



Now Create a folder where you will put your Objective-C code files. I have created a folder named 'Example1' in the following path
c:\Object-C\Example1
Then I have created the following files for this simple project

filename: Myclass.h
This file declares a Interface for the MyClass object

#import

@interface MyClass:NSObject{
int n;
}
-(void) setn: (int) a;
-(int) getn;
-(int) sum: (int) a andb: (int) b andc:(int)c;
@end

In the above code I have create a class name MyClass. MyClass is inherited from the NSObject class The MyClass has one instance integer variable 'n' and three instance methods.

file: MyClass.m
This file implements the MyClass Object

#import "Myclass.h"

@implementation MyClass

- (void) setn: (int) a

{
n=a; }
-(int) getn { return n; }
- (int) sum: (int) a andb: (int) b andc:(int)c
{ return a+b+c; }
@end

file: main.m
This the main program file

#import
#import"Myclass.h"
int main()
{

MyClass *class = [[MyClass alloc]init];
[class setn: 5];
printf("Sum is : %d",[class sum : [class getn] andb : [class getn] andc: [class getn]]);
[class release];

return 0;
}
Now type the following text in your opened shell prompt ('msys.bat')

$ cd /c/Object-C/Example1






It will take you to the folder where all codes are

$ ls














Now type the following command in the prompt

$ gcc -o Myclass Myclass.m main.m -I /c/GNUStep/GNUStep/System/Library/Headers -L /c/GNUStep/GNUStep/System/Library/Libraries -lobjc -lgnustep-base



A new file Myclass.exe will be created in the Example1 folder.

run the Myclass.exe file

see the output

Enjoy!!!!