5

有什么方法可以在不使用 GNUStep 的情况下在 ubuntu 上编译目标 c 程序?我想使用默认的 C 标准库,除了 Objective-C 的 OOB 语法。我现在遇到的问题是,一旦我掌握了所有方法,我需要一种方法来调用它们。在 Mac 中,我只会分配并初始化它,但在 Linux 上,当我尝试编译它时,clang 只会给我一个错误。

#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"];
}
4

2 回答 2

1

您可以使用 gcc 编译 Objective-c,但请记住使用 -lobjc 开关,以便编译器知道您使用的是什么语言。

您还需要包含以下标题:

    #import <objc/Object.h>

...并从您的界面扩展对象。在此处查看 Objective-c 的 hello world 示例:

http://en.m.wikipedia.org/wiki/List_of_Hello_world_program_examples#O

于 2013-06-02T10:49:58.953 回答
1

好问题 - 它让我自己深入研究这些问题,因为我想用普通语言 (C/ObjC) 重写几个旧的 Python 项目,所以我的目标是远离 Crap++ 并避免 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

Foo.m

#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

主.m

#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 $@

我得到的输出:

+[Foo alloc]
-[Foo init]
-[Foo get_bar]
old bar: 31
-[Foo set:bar:]
-[Foo get_bar]
new bar: 10

看起来它有效!

于 2020-01-07T09:38:18.947 回答