6

由于 Objective-C 是 C 的超集,所有 Objective-C 特定的语句都在编译 .m 文件期间转换为 C 语句(我猜是由预处理器)。因此,例如,消息表达式 like[receiver method]被转换为对消息传递函数的调用objc_msgSend(receiver, selector)

我的问题是:如果我有这样的类定义:

@interface ClassA {
    int var1;
    float var2;
    id var3;
}

-(void) method1;
-(int) method2: (int) num1;
@end

@implementation ClassA
-(void) method1 {
    // Implementation of the method
}

-(int) method2: (int) num1 {
    // Implementation of the method
}

@end

它被编译器转换成什么(在 2.0 版本的 Objective-C 中)?它是否被转换为对函数的调用,如objc_allocateClassPair()、和来自可执行文件的结构)?class_addIvar()class_addMethod()objc_registerClassPair()

4

1 回答 1

14

由于 Objective-C 是 C 的超集,所有 Objective-C 特定的语句都在编译 .m 文件期间转换为 C 语句(我猜是由预处理器)。

在 1988 年确实如此。虽然 Objective-C仍然可以以这种方式编译,但时间不长了。

The compiler parses Objective-C, along with C and-- sometimes-- C++, and emits an abstract syntax tree [AST] that represents the post-preprocessed output. That AST includes the various Objective-C definitions quite directly.

Note that the details of GCC's compilation and LLVM's compilation are diverging.

If you look at the compiled output, you'll see that the mach-o file -- the executable product -- has various sections in the file that contain the Objective-C metadata including class definitions, selector tables, ivar layout, etc... The compiler generates this metadata into the .o file and then the linker mashes it all together, eliminates duplicate information (that isn't a duplicate symbol), and writes the mach-o.

As someone mentioned in a different question, you can use the Objective-C rewriter to rewrite Objective-C to straight C, but the resulting code is inefficient and quite a bit different than the regulation compilation pipeline.

于 2012-08-07T14:09:17.487 回答