用gcc 4.6.2编译目标C.

Ana*_*man 2 objective-c

我试图在Windows上学习目标c.我的程序编译警告

我的代码是

#include <objc/Object.h>

@interface Greeter:Object
{
  /* This is left empty on purpose:
   ** Normally instance variables would be declared here,
   ** but these are not used in our example.
   */
}

- (void)greet;

@end

#include <stdio.h>

@implementation Greeter

- (void)greet
{
    printf("Hello, World!\n");
}

@end

#include <stdlib.h>

int main(void)
{
    id myGreeter;
    myGreeter=[[Greeter alloc] init];
    [myGreeter greet];
    [myGreeter release];
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

我使用以下命令在GNUStep上编译我的程序

 gcc -o Greeter Greeter.m -I /GNUstep/System/Library/Headers -L /GNUstep/System/Libra
 /Libraries -lobjc -lgnustep-base -fconstant-string-class=NSConstantString
Run Code Online (Sandbox Code Playgroud)

我在编译时收到以下警告

: 'Greeter' may not respond to '+alloc' [enabled by default]
: (Messages without a matching method signature [enabled by default]
: will be assumed to return 'id' and accept [enabled by default]
: '...' as arguments.) [enabled by default]
: no '-init' method found [enabled by default]
: no '-release' method found [enabled by default]
Run Code Online (Sandbox Code Playgroud)

因此,当我运行我的可执行文件时,对象不会被实例化.

我正在使用MinGW的gcc,其中gcc版本是4.6.2

--update ---

当我从NSObject而不是Object扩展时,程序运行正常

- 更新2 ----

我的Object.h看起来像

#include <objc/runtime.h>

@interface Object
{
    Class isa;
}
@end
Run Code Online (Sandbox Code Playgroud)

- 更新3 ----

我修改了我的代码如下.编译很好,但我不确定这是否是正确的方法

@interface Greeter
{
  /* This is left empty on purpose:
   ** Normally instance variables would be declared here,
   ** but these are not used in our example.
   */
}

- (void)greet;

+ (id)alloc;
- (id)init;
- release;

@end

#include <stdio.h>

@implementation Greeter

- (void)greet
{
    printf("Hello, World!\n");
}

+ (id)alloc
  {
    printf("Object created");
    return self;
  }

- (id)init
  {
    printf("Object instantiated");
    return self;
  }

- release {}

@end

#include <stdlib.h>

int main(void)
{
    id myGreeter;
    myGreeter=[[Greeter alloc] init];
    [myGreeter greet];
    [myGreeter release];
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

bbu*_*bum 18

除非您正在研究Objective-C的历史,否则尝试基于Object类学习语言完全是浪费时间.在Object最后的一类普遍在1994年预NEXTSTEP根类.

如果你的目标学习1994年以前的Objective-C,那么请说明,因为如果是这样,你到目前为止所得的答案是完全错误的.即使目标是采用现代模式,答案也更符合How do I recreate NSObject?其他任何方面.请注意,如果是你的目标......那么......去吧!1994年以前的Objective-C有点像OOP宏观组装,通过这种方式,金属的简单性有了很大的力量.

例如,你说"我已经修改了我的代码如下.它编译得很好,但我不确定这是否是正确的方法".

该代码编译,但是 - 不 - 它不起作用.一点也不.对于初学者来说,该+alloc方法实际上并没有分配任何东西.Greeter该类也没有实现足够的功能来执行任何类似的操作NSObject.

如果您的目标是学习类似于现代Objective-C的东西并使用Windows这样做,最好的方法可能是安装GNUStep工具链.至少,你将使用NSObject类似于现代Cocoa(以及在较小程度上,iOS)的一组根源API 进行编程.

如果您的目标是学习真正的现代Objective-C,那么您至少需要一个可以运行最新版LLVM的环境.当然,如果您想编写基于Objective-C的iOS或Mac OS X应用程序,您将需要运行Lion的Mac.