Jump to content

How to get C++ and Objective-C to play nicely in XCode

+ 2
  Paul Zirkle's Photo
Posted Nov 10 2009 09:28 AM

If you're like me, developing games for the iPhone, you need to merge the utility of the Cocoa interface using Objective-C with the performance (and possibly existing code-bases) of C++.

When you're first beginning to merge C++ and Obj-C code, things can get a little hairy, but if you follow two rules, things should be easy:
1) use .MM instead of .M or .CPP -- this will cause XCode to use the right compiler ("cpp.objcpp" instead of "c.objc") when building these files

2) do not allow any C++ code inside of a .H file that is visible from .M files


The first step is pretty easy; just rename files to .MM (yes, even your AppDelegate.m if you need to).

The second step is a little less obvious, but still just as simple. If you're compiling a .M file and it #includes or #imports anything (which #includes or #imports something else, and so on) that eventually reaches C++ code (such as a class definition), you will get a compiler error because the compiler being used ("c.objc") won't recognize the C++ code.

To fix the problem, either:
A) break the #include/#import chain that links from the .M file to the .H file with the C++ code in it,
B) move the C++ code out of the .H file (if its only used inside of one .CPP or .MM file, you can safely move the definition into that file) or,
C) consider changing the .M file into an .MM file

Tags:
0 Subscribe


0 Replies