简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM