Ubuntu12でObj-Cを叩いてみる

多少癖があったのでメモ。
このあたりを参考に...

install

以下の2つ。Obj-CコンパイラとNSObjectのライブラリ。

$ sudo apt-get install gobjc libgnustep-base-dev

コンパイル

以下のコードで実験。

#import <Cocoa/Cocoa.h>

@interface MyClass : NSObject
- (void) getMessage;
@end

@implementation MyClass
- (void) getMessage
{
  @try {
    NSLog(@"Hello");
    @throw [[NSException alloc] initWithName:@"myException" reason:@"myReason" userInfo:nil];
  }
  @catch (NSException* e) {
    NSLog(@"%@", e);
  }
}
@end

int main(int argc, char* argv[])
{
  id obj = [MyClass alloc];
  [obj getMessage];

  return 0;
}
$ gcc test.m -o test -lobjc -lgnustep-base \
 -I/usr/include/GNUstep/ \
 -fconstant-string-class=NSConstantString \
 -D_NATIVE_OBJC_EXCEPTIONS -fobjc-exceptions
  • -lgnustep-base : NSObject系列を使うために。
  • -fconstant-string-class=NSConstantString : @"string"と書くために。
  • -D_NATIVE_OBJC_EXCEPTIONS -fobjc-exceptions : @try/@catchを使うために。