在ubuntu上不使用gnustep编译objective-c程序
有没有办法不用GNUStep在ubuntu上编译objective c程序?我想使用默认的C标准库和Objective-C的OOB语法。我现在的问题是,一旦我有了所有的方法,我需要一种方法来调用它们。在Mac中,我只需要alloc和init,但在Linux上,当我试图编译它时,clang只会给我一个错误在ubuntu上不使用gnustep编译objective-c程序,objective-c,c,computer-science,Objective C,C,Computer Science,有没有办法不用GNUStep在ubuntu上编译objective c程序?我想使用默认的C标准库和Objective-C的OOB语法。我现在的问题是,一旦我有了所有的方法,我需要一种方法来调用它们。在Mac中,我只需要alloc和init,但在Linux上,当我试图编译它时,clang只会给我一个错误 #include <stdio.h> // C standard IO library (for printf) #include <stdlib.h> // C sta
#include <stdio.h> // C standard IO library (for printf)
#include <stdlib.h> // C standard library
// Interface
@interface test
-(void)sayHello :(char *)message;
@end
// Implementation
@implementation test
-(void)sayHello :(char *)message {
printf("%s", message);
}
int main(int argc, char *argv[]) {
test *test = [[test alloc] init];
[test sayHello:"Hello world"];
}
#包括//C标准IO库(用于printf)
#include//C标准库
//接口
@接口测试
-(void)sayHello:(char*)消息;
@结束
//实施
@实施测试
-(void)sayHello:(char*)消息{
printf(“%s”,消息);
}
int main(int argc,char*argv[]){
test*test=[[test alloc]init];
[测试说你好:“你好,世界”];
}
您可以使用gcc编译objective-c,但请记住使用-lobjc开关,以便编译器知道您使用的语言
您还需要包括以下标题:
#import <objc/Object.h>
#导入
…并从接口扩展对象。请参见objective-c的hello world示例:
好问题-这让我自己深入研究了这些问题,因为我想用普通语言(C/ObjC)重写几个旧的Python项目,所以我的目标是远离垃圾++并避免GNUstep开销。下面是我的尝试和测试解决方案: Foo.h:
#import <objc/Object.h>
@interface Foo: Object
{
@private
int
bar;
}
+ (id) alloc;
+ (id) new;
- (id) init;
- (id) set_bar: (int)value;
- (int) get_bar;
@end
#import <stdio.h>
#import <objc/runtime.h>
#import "Foo.h"
@implementation Foo
+ (id) alloc
{
puts(__func__);
return class_createInstance(self, 0);
}
+ (id) new
{
return [[self alloc] init];
}
- (id) init
{
puts(__func__);
bar = 31;
return self;
}
- (id) set_bar: (int)value
{
puts(__func__);
bar = value;
return self;
}
- (int) get_bar
{
puts(__func__);
return bar;
}
@end
#import <stdio.h>
#import "Foo.h"
int
main
()
{
id
foo = [Foo new];
printf("old bar: %i\n", [foo get_bar]);
[foo set_bar: 10];
printf("new bar: %i\n", [foo get_bar]);
return 0;
}
run: main.o Foo.o
gcc $^ -o $@ -lobjc
main.o: main.m Foo.h
gcc -c $< -o $@
Foo.o: Foo.m Foo.h
gcc -c $< -o $@
看起来很有效 如果没有GNUStep(或Objective-C运行时库),
alloc
和init
的实现将从何而来?是的,有没有办法从没有alloc
或init
的实现中调用方法?现代GNUStep运行时既不实现+alloc也不实现-init。如果需要,可以在任何地方重写实现。+alloc的实现应该只调用类_createInstance(…),其余必要的API请参考您的.h。您可能还想考虑如何使用@ AutoRelayIe。如何管理保留计数器等。我不知道为什么人们会真的想走那条路线,只要安装GNUSTEP基金会。谢谢各位的帮助!但我找到了解决办法。:)正是我想要的。非常感谢D我为那些使用Ubuntu的人找到的另一个指南,如果你使用现代GNUstep运行时,这个解决方案将不起作用。它没有实现这些方法,一旦你想要clang的objective-c方言,事情就会破裂。我个人不会这么做。我正在尽量避免GNUstep。我希望代码尽可能地使用C语言,并带有一些面向对象的特性,比如C语言的实现和接口
+[Foo alloc]
-[Foo init]
-[Foo get_bar]
old bar: 31
-[Foo set:bar:]
-[Foo get_bar]
new bar: 10