How do I compile Objective-C code with GCC?

When I try to compile this code, I got the 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 code line: g ++ -x objective-c ++ test.mm -otest -lobjc

I get the following warnings when compiling:

test.mm:11:14: warning: ‘Objectmay 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 returnidand accept
[enabled by default]
test.mm:11:14: warning: ‘...’ as arguments.) [enabled by default]
test.mm: In functionint main()’:
test.mm:19:28: warning: ‘Hellomay not respond to ‘+new[enabled by default]
test.mm:21:14: warning: ‘Hellomay not respond to-free[enabled by default]

      

and if i try to run - i get SIGSEGV:

$> ./test
$> Segmentation fault

      

What am I doing wrong?

env: linux-x86_64, gcc-4.7.2

Thank.

+3


source to share


1 answer


This code is incorrect. And ancient. It would never work. Now it will have (corrected and added some additional examples).

First check if GNUStep is installed. If you do, switch to using NSObject and libFoundation (actually libgnustep-base

, as Fred points out in the comments).



Secondly, [IIRC - Scratched Old Brain Cells] that init

were still returned (id) when Object was still the root class. Since you are not doing anything useful with this method init

, just remove it entirely.

Compiler errors indicate that your subclass is Hello

not properly inheriting from Object

, which makes no sense.

+3


source







All Articles