niXman
niXman

Reputation: 1758

How to compile Objective-C code with GCC?

When I try to compile this code that I got form here with gcc:

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

@interface Hello: Object
- (void) init;
- (void) say;
@end

@implementation Hello
- (void) init {
  [super init];
}
- (void) say {
  printf("Hello, world!\n");
}
@end

int main() {
  Hello *hello = [Hello new];
  [hello say];
  [hello free];
  return 0;
}

with comand line: g++ -x objective-c++ test.mm -otest -lobjc

When compiling I get the following warnings:

test.mm:11:14: warning: ‘Object’ may not respond to ‘-init’ [enabled by default]
test.mm:11:14: warning: (Messages without a matching method signature
[enabled by default]
test.mm:11:14: warning: will be assumed to return ‘id’ and accept
[enabled by default]
test.mm:11:14: warning: ‘...’ as arguments.) [enabled by default]
test.mm: In function ‘int main()’:
test.mm:19:28: warning: ‘Hello’ may not respond to ‘+new’ [enabled by default]
test.mm:21:14: warning: ‘Hello’ may not respond to ‘-free’ [enabled by default]

and if I try to run - I get SIGSEGV:

$> ./test
$> Segmentation fault

What I am doing wrongly?

env: linux-x86_64, gcc-4.7.2

Thanks.

Upvotes: 4

Views: 5178

Answers (1)

bbum
bbum

Reputation: 162722

That code is wrong. And ancient. It would never have worked. Now it would have (fixed and added some additional examples).

First, check to see if you have GNUStep installed. If you do, switch to using NSObject and libFoundation (actually libgnustep-base, as Fred points out in the comments).

Secondly, [IIRC -- scratching old brain cells here] that init still returned (id) when Object was still the root class. Since you aren't doing anything useful in that init method, just delete it entirely.

The compiler errors indicate that your Hello subclass is not correctly inheriting from Object, which makes no sense.

Upvotes: 3

Related Questions