Many thanks to Justin Souter, who solved the problem so clearly and easily.

With Xcode, you can write files as either Objective-C, which adds the special ‘Objective’ stuff to the basic C language, or as Objective-C++, which does the same for C++. Because of the existence of Obj-C++, it is easy to use C++ libraries in Cocoa applications. The most straightforward way to do so is to write an Objective-C++ class that encapsulates the C++ class, presenting an Obj-C interface for use in other parts of the application. Unfortunately, if the Obj-C++ header file includes the C++ header that contains the class definition, then every Obj-C file that includes the Obj-C++ wrapper class must also be compiled as Obj-C++, since it is implicitly including the C++ class definition. It would be ideal if only the Obj-C++ wrapper class needed to be compiled as Obj-C++, with everything else being simple Obj-C.

It turns out that the problem is readily solved with preprocessor commands that hide the C++ class definition include from the Obj-C files. To do that, add the following to the WrapperClass.h header file:

 #ifdef __cplusplus
 // Obj-C++ code goes here
 class ClassBeingWrapped;
 #ifdef __OBJC__
 #ifndef __cplusplus
 // Obj-C code goes here
 typedef void ClassBeingWrapped;

So simple that I’m embarrassed I didn’t think of it myself.

Published on 13 November 2010 and tagged as
Browse articles... Browse tags...