Ubuntu18.04 如何解决编译objective-c出现undefined reference to objc_get_class

    今天通过Ubuntu18.04.1安装基于gcc的objective-c编译环境,出现了一个问题,找不到objective相关的文件符号。

    HelloWorld.m源码如下

int main(int argc, const char* argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSLog(@"hello world");
    [pool drain];
    return 0;
}

编译命令:

$ gcc `gnustep-config --objc-flags` -lobjc -lgnustep-base HelloWord.m -o hello.o

出错如下错误信息:

/tmp/cch0DQEt.o: In function `main':
/home/XX/ios-projects/objective-c-demo/HelloWord.m:4: undefined reference to `objc_get_class'
/home/XX/ios-projects/objective-c-demo/HelloWord.m:4: undefined reference to `objc_msg_lookup'
/home/XX/ios-projects/objective-c-demo/HelloWord.m:4: undefined reference to `objc_msg_lookup'
/home/XX/ios-projects/objective-c-demo/HelloWord.m:6: undefined reference to `NSLog'
/home/XX/ios-projects/objective-c-demo/HelloWord.m:7: undefined reference to `objc_msg_lookup'
/tmp/cch0DQEt.o: In function `__objc_gnu_init':
/home/XX/ios-projects/objective-c-demo/HelloWord.m:9: undefined reference to `__objc_exec_class'
/tmp/cch0DQEt.o:(.data.rel+0x0): undefined reference to `__objc_class_name_NSConstantString'
/tmp/cch0DQEt.o:(.data.rel+0x8): undefined reference to `__objc_class_name_NSAutoreleasePool'
collect2: error: ld returned 1 exit status

 

       一开始还以为是环境问题,重启系统也没有用,照着网上教程安装后敲命令也不行。

折腾了一个小时以后,终于翻到了stackflow的一个答案,需要增加参数-Wl,--no-as-needed,原因是在编译链接阶段,由于HelloWorld.m在命令行的后面,导致前面没有发现对应的文件符号,进而失败。

原文如下:

 

https://stackoverflow.com/questions/11425120/objective-c-on-linux-compile-error

 

于是调整编译命令:

$ gcc `gnustep-config --objc-flags` -Wl,--no-as-needed -lobjc -lgnustep-base HelloWord.m -o hello.o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值