已编辑
我一直在尝试开始用Objective-c编码。它只是一个尝试getter和setter方法的简单程序。同时打印"你好世界"。以下是我的代码:
#import <objc/Object.h>
@interface Car:Object{
int wheel: 5;
}
- (int)wheel;
- (void)setWheel: (int)newWheel;
@end
#include <stdio.h>
@implementation Car
- (int)wheel{
return wheel;
}
- (void)setWheel: (int)newWheel{
wheel = newWheel;
}
@end
#include <stdlib.h>
int main(void){
printf("Hello World");
}
我现在得到垃圾
/tmp/cc3UC6jY.o: In function `__objc_gnu_init':
hello.m:(.text+0x6d): undefined reference to `__objc_exec_class'
/tmp/cc3UC6jY.o:(.data+0x1c0): undefined reference to `__objc_class_name_Object'
collect2: error: ld returned 1 exit status
我使用了命令gcc -o hello hello.m -lobjc
我花了几个小时在谷歌上搜索这个答案。
您的代码的以下变体为我编译并运行:
#import <objc/Object.h>
@interface Car : Object {
int wheel;
}
- (int)wheel;
- (void)setWheel: (int)newWheel;
@end
@implementation Car
- init {
wheel = 5;
return self;
}
- (int)wheel {
return wheel;
}
- (void)setWheel: (int) newWheel {
wheel = newWheel;
}
@end
#include <stdio.h>
int main(void){
printf("Hello Worldn");
id myCar = [[Car alloc] init];
printf("Wheel value is %dn", [myCar wheel]);
return 0;
}