目标C中__OBJC__

Cas*_*ash 25 objective-c

__OBJC__Objective C 中的含义是什么?

#import <Availability.h>

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
#endif
Run Code Online (Sandbox Code Playgroud)

Chr*_*cke 34

这意味着正在使用目标C编译器.因此,您可以创建可在编译目标C或C或C++时使用的混合头文件.

你可以在这样的头文件中使用它,如果你想发布一个头文件来定义一个你希望c和c ++程序员/代码可用的目标c对象:

#ifndef MYHEADER_H
#define MYHEADER_H

#ifdef __OBJC__
// Put objective C things in this block
// This is an objc object implemented in a .m or .mm file
@implementation some_objc_object {
}
@end
#endif

#ifdef __cplusplus
#define CLINKAGE "C"
// c++ things that .m or .c files wont understand go in here
// This class, in a .mm file, would be able to call the obj-c objects methods
// but present a c++ interface that could be called from c++ code in .cc or .cpp 
// files
class SomeClassThatWrapsAnObjCObject
{
  id idTheObject;
public:
  // ...
};
#endif
// and here you can declare c functions and structs
// this function could be used from a .c file to call to a .m file and do something
// with the object identified by id obj
extern CLINKAGE somefunction(id obj, ...); 
#endif // MYHEADER_H
Run Code Online (Sandbox Code Playgroud)


Sev*_*yev 28

这看起来像是预编译的头文件.

预编译的头文件在项目中的所有C-dialect文件之间共享.就好像所有.c,.cpp,.m和.mm文件都有一个不可见的#include指令作为第一行.但是Cocoa头文件是纯粹的Objective C - 尝试将它们包含在C/C++源代码中只会产生语法错误.因此#ifdef.

如果您的项目仅包含Objective C文件(.m/.mm),这是典型情况,则#ifdef不是必需的.但是Xcode,它首先生成了这个标题,保护你所有的一切.

即使它不是PCH文件,如果要从Objective C和普通C/C++中包含该文件,这个#ifdef才有意义.但无论如何都没有伤害.