Search code examples
objective-cxcode4objective-c++

Any downside to never creating ObjC files but always creating ObjC++ files instead?


By default Xcode creates both an .h and and an .m file when you ask for a new ObjC class. Everything works fine until you need to refer to any C++ file elsewhere in your project and start #import ing it into either your .h or .m file

At that point, the ObjC compiler gest utterly confused and throws mountains of parsing errors, and you the user (that is to say: me) get even more confused until such time it hits me: of course I should make that file an ObjC++ file instead.

The options are:

  1. tell Xcode that this particular file, even though it is a .m file really is an ObjC++ file, or
  2. rename that file to .mm.

The first option is not very palatable to me, because that file really is ObjC++ regardless of the what the project thinks it is.

The second option is not good either as it screws up the Git repo which then 'forgets' that there used to be another .m file which really is the history of this 'new' .mm file.

So I have decided from now on to always rename any .m file that Xcode creates for me to .mm first thing after creating it so that I won't loose the history.

It has worked well for me so far, but I have this slight worry in my head, that there might be some corner case where I would really want to have an ObjC file and not an ObjC++ file.

What would those corner cases be? Anyone is aware of any ObjC++ file which happens to NOT contain any C++ reference but would choke the ObjC compiler in some way, just by virtue of being an .mm file?

And if there are no downside, why not just deprecate the use of .m forever and stick to .mm instead?


Solution

  • There is no downside, although there are two methods created on behalf of you (.cxx_construct and .cxx_destruct), but they are only used for crafting and destroying C++ objects when you create/dealloc an instance. If your class has no C++ members, these functions do nothing and add only an really extremely low overhead. Otherwise, you still have C functions generated for your Objective-C methods, not C++ functions.