views:

51

answers:

3

Hi,

I have to create a iOS Programm using Code of some C++ POSIX Classes. I already read the "Using C++ With Objective-C" manual of the Apple Developer Center. They describe how to mix C++ & Objective C code in a .mm file.

My question is, is there any possibility to use the C++ Classes in my .h/.m files of a normal Objective C Project?

Or is it necessary to write the hole Project in that .mm file style with its own main?

A: 

You have to force compilation of the Obj-C files in which you want to use C++ to Obj-C++ in the build menu. You can then create and use C++ objects in your Obj-C classes.

Chaoz
Why not just name the implementation files with the .mm extension? Then you don't need to force anything in the project.
Peter Hosey
Depends on if you want to reuse these files for a project other than an iOS one.
Chaoz
Where can you use an Objective-C (.m) file where you can't use an Objective-C++ (.mm) file?
Peter Hosey
+1  A: 

You can combine in a project any types of files, say .c, .m, .cpp and .mm, and the compiler is chosen automatically depending on the extension. For example, you can keep the standard main.m file which comes with the XCode template, and add your new .h and .mm files to use Objective-C++.

In other words, there's no distinction between a normal Objective-C project and a Objective-C++ project. You just have to use .mm extension for the specific files which needs Objective-C++. This can be used in any project.

Yuji
Okay for example I have a normal iPhone Project and I want to use an in C++ written Class in a view controller. It is not possible just to include the .h file of the C++ Code for using the C++ classes. Is there anything I forgot?
You can. You just need to change the extension of your view controller implementation file from `.m` to `.mm`. You can change the file name inside XCode.
Yuji
A: 

It depends on how you want to use the C++. In my projects I usually only make a few calls out to do some heavy lifting, etc.

What I do is have C++ in .cpp files, then create a few .mm files that have headers that have no C++ in them. These .mm files are obj-c wrappers for the C++. Then the C++ is 'contained' to the original posix files, plus a few files that give the C++ classes and calls all the interface you need. As few .mm files as possible is a good thing.

Keeping the C++ out of most of your code makes debugging, etc easier.

--Tom

Tom Andersen