What is #ifdef __OBJC__ and why are the libraries listed below?

I believe that the #ifdef __OBJC__ directive ensures that I import the following class libraries for Objective-C only. What is the purpose of listing class libraries after an ifdef ? Can't this code example defeat the goal?

 #ifdef __OBJC__ #import <foundation/foundation.h> #import <uikit/uikit.h> #import <coredata/coredata.h> #endif </coredata/coredata.h></uikit/uikit.h></foundation/foundation.h> 
+4
source share
4 answers

Objective-C is a superset of C (like C ++), and quite often files from different languages ​​will be used in the same project and share headers, especially the prefix header. #ifdef __OBJC__ , for example #ifdef __cplusplus , allows you to include (or #import for Objective-C) headers only for the corresponding language.

The same header included in .c, .cpp and .m files (with default compiler settings) will only have __OBJ__ for .m files.

+3
source

Basically in this code, if you use Objective-C, it imports these 3 libraries

 #import <foundation/foundation.h> #import <uikit/uikit.h> #import <coredata/coredata.h> 

The purpose of this, if, is to not import them if necessary.

0
source

They are listed after #endif as a reminder, so it makes code easier to read. Otherwise, you will need to look up to see that #endif ends.

0
source

The reason for this is that this code can still be compatible with regular C code that can use the functionality in this C file (at least as it seems to me). By including these libraries only when the OBJC is defined, it ensures that the libraries are ONLY imported when you compile for target c, and not for standard C.

0
source

All Articles