phix23 phix23 - 4 months ago 27
Objective-C Question

How to detect C++ compiler with macro in Xcode?

I'm mixing Objective-C (*.m) and Objective-C++ (*.mm) source files in an iOS project.
When I import a C++ header file in a *.m file how can I exclude the C++-specific code in the header file? I want to use a compiler macro, something like:

// SomeClass.h - a file I want to import in C++ and Objectice-C classes

#if CPLUSPLUS
#import "CPlusPlusLibrary.h"
#endif

@interface SomeClass : BaseClass
{

#if CPLUSPLUS
CPlusPlusClass* variable;
#endif

}

@end

Answer

Objective-C++ is a viral thing that you can't really stop. Your current example gives different parts of your code (C and C++) a different view of the layout of your class, and while I do think it would still work, I'm pretty sure this isn't a very good thing.

When working on ObjC projects interacting with C++, I usually try to avoid having C++ references in my header files. This makes the header file valid for both Objective-C and Objective-C++. If I can't avoid it, then I don't try to fight it (it's a lost cause); but I try to not include that ObjC++ header file in otherwise 'sane' ObjC headers, and I use the @class directive (@class SomeObjCPPClass; instead of an #import "SomeObjCPPClass.h" directive) instead if I need to reference the class. Then, I include the header from the implementation file, which has to be ObjC++, but at least it won't propagate from there.

EDIT Recent-ish (2012 and later) versions of Clang allow you to declare fields in the @implementation side of things. This can effectively free your header of any references to C++ and make Objective-C++ much more manageable (and less viral). To retain OP's example, you would now have:

// SomeClass.h - a file I want to import in C++ and Objectice-C classes

@interface SomeClass : BaseClass

// (no fields)

// (methods)

@end

// SomeClass.mm
#import "CPlusPlusLibrary.h"

@implementation SomeClass
{
    CPlusPlusClass* variable;
}

// (method implementations)

@end

This makes the SomeClass.h header safe to include in pure Objective-C files and Objective-C++ files as well.