Unable to compile Objective-C code on Ubuntu

微笑、不失礼 提交于 2019-12-11 10:23:31

问题


So I have this piece of code...

/**
 * cdb.m
 * Copyright (C) 2013 Naveen Mathew. All rights reserved.
 */

#import <objc/Object.h>
#import "cdb.h"
#import <stdio.h>
#import <stdlib.h>

@implementation CDB : Object
{

}

- (int) main {
    printf("Hello world");
    return 0;
}

@end

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

    return 0;
}

and I want to compile it in Ubuntu 13.04 but without all the crap that GNUStep gives me. So I use the GNU Objective C runtime (gobjc) but when I compile I get the following...

clang -Wall -lobjc -o cdb cdb.m -I/usr/lib/gcc/x86_64-linux-gnu/4.7/include
cdb.m:25:21: warning: class method '+new' not found (return type defaults to
      'id') [-Wobjc-method-access]
        CDB *myNumber = [CDB new]; // equal to [[Number alloc] init]
                        ^    ~~~
1 warning generated.

and when I run the program I get a segmentation fault... I'm using gobjc 4.7. I tried it with gobjc 4.6... it compiles but I still get a segmentation fault...


回答1:


I think some ancient runtime has +new and friends implemented. For newer runtime like gnustep-runtime including one came with GCC which is very different, I think, you must implement your own craps using category or whatsoever. You can just cut & paste GNUstep's implementation of NSObject but it could be too tricky for you as it does things like prefixing the malloc with retain counter et al, else you may want to implement your own way to maintain ref counting like using hash map or anything. You may also try alternate framework like ObjFW if GNUstep-base alone has too much craps for you.




回答2:


+(id)new is a function of the NSObject class. However, you are subclassing a runtime object. To use most of the Apple methods you're used to using in OS X, you'll need to subclass NSObject instead.

Also, you declare an object's superclass in the interface, not the implementation. You need to change @implementation CDB : NSObject to @implementation CDB, then, in your header file, place @interface CDB : NSObject { ...



来源:https://stackoverflow.com/questions/18038430/unable-to-compile-objective-c-code-on-ubuntu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!