Ufo.rob
Ufo.rob

Reputation: 141

Why does this code work for clang and not in gcc?

Here a piece of code I found on a forum in a thread about programming in Objective-C with gcc on Ubuntu (and not clang) but it only works with clang (on Ubuntu)! From code you easily understand this is the very first time I'm trying to do something in Objective-C (I know C and C++ and this try is propedeutic to future programming for iOS)

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

@interface Number: Object
{
@public
    int number;

}

- (void)printNum;

@end

@implementation Number: Object


- (void)printNum
{
    printf("%d\n", number);
}

@end

int main(void)
{
    Number *myNumber = [Number new]; // equal to [[Number alloc] init]

    myNumber->number = 6;

    [myNumber printNum];

    return 0;
}

This works OK in clang but in gcc it compiles with warning and gives segmentation fault in execution.

$ gcc -o prova.out prova.m -lobjc
prova.m: In function ‘main’:
prova.m:28:5: warning: ‘Number’ may not respond to ‘+new’ [enabled by default]
prova.m:28:5: warning: (Messages without a matching method signature [enabled by default]
prova.m:28:5: warning: will be assumed to return ‘id’ and accept [enabled by default]
prova.m:28:5: warning: ‘...’ as arguments.) [enabled by default]
$ ./prova.out
Errore di segmentazione (core dump creato)

Upvotes: 1

Views: 393

Answers (1)

bbum
bbum

Reputation: 162722

Object; wow. That be old school.

Unless your Object class defines a +new class method, then your subclass isn't going to respond to that method. You either need to implement new or eliminate the call to new.

That it is compiling with one compiler but not the other smells like you are compiling against two different versions of the runtime.

Upvotes: 3

Related Questions