Monday, 27 April 2009

Objective C++ and file extensions (.m, .mm, .cpp)

If you've ever wondered how to combine C++ and C in your Cocoa code for iPhone or Mac, it is as simple as renaming your files to have a .mm extension, rather than the default .m extension.

It is a shame that Apple don't enable this file extension by default in their code building wizards. It certainly makes the transition to Objective C for C++ programmers a lot easier!

Anyways, for those of you interested in porting your C++ code across to iPhone and Cocoa, without having to rename your files or create lots of .mm file wrappers; I discovered under Linux that -x objective-c++ can be used to tell the compiler to treat the file as an objective c++ file; irrespective of the file extension... as follows (wbere test.cpp actually contains Objective-C++ syntax, and would normally be called ...):

gcc-4 -x objective-c++ test.cpp -lgcc -lobjc -o a.exe -lc -lstdc++

There are two ways to use this in XCode:
- on file-by-file basis, right-click on any .cpp file in which you want to put some Objective-C and/or C++, and select Get Info. In the Build tab, set -x objective-c++ in the Additional Compiler Flags field.
- alternatively, for the entire project, in Project Settings under Build, under GCC 4.0 - Language, set Compile Sources As to Objective-C++.

As always; this is easy when you know how...!



David said...

Sure as hell makes it easier than changing everything to .mm. Thanks!

Pete Cole said...

Glad to have helped! :)

REETU RAJ said...

Thanks, It helped.
I posted credit to you on my post :)

Pete Cole said...

Happy to help! :)