Monday, May 25, 2009

Figuring out Objective-C++

Today I was tinkering with Xcode and Objective-C while trying to think up some ideas for iPhone apps. Eventually, I found myself trying to get some C++ code to compile and execute in the small iPhone test project I had setup and running. Getting this to work actually took me a bit of time to figure out, and looking back I think it's because I had some trouble grasping the conceptual idea of how Objective-C/C++ and vanilla C++ interact.

I started out creating a new C++ class MyTest with a .cpp and .h file. Once that was compiling, I tried hooking the MyTest class into the project's main.m file by include'ing the .h file and calling:

MyTest* test = new MyTest();

Needless to say, the compiler would have none and this made its opinion very clear with several errors. After reading up on Google and toying around, it finally hit me what I'd done wrong. The problem here is 'new' is C++ syntax, and the main.m file is being compiled as an Objective-C file(courtesy of the .m extension), so the compiler didn't understand what was going on. Additionally, my class's header file wasn't being properly read because it contained a C++ class definition, not an Objective-C definition. Once this light went off, I understood why the Objective-C++ (.mm) extension is needed; it allows Objective-C and C++ syntax to co-exist within the same file. To fix this, I hooked the MyTest C++ .h and instantiation into a separate Obj-C class file and changed the extension on said file to .mm. This compiled and ran just as I expected.

No comments:

Post a Comment