Mixing C++ and Objc++

Discussion in 'Mac Programming' started by imaxx, Aug 13, 2009.

  1. imaxx macrumors newbie

    Aug 13, 2009

    I have a slight problem with MAC (well, iphone target, but this is a more general problem) and Obj c++ (I am at the sea atm so i have some problem compiling).
    I have the following code:
               static NSString* uniqueID = nil;
               const char *pID;
    	uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
    	uniqueID = [[[uniqueID uppercaseString] stringByReplacingOccurrencesOfString:@":" withString:@"-"] copy];
    	pID = [uniqueID UTF8String];
    and my problem is: will this code run if included WITHIN a ".cpp" file? What do I need to do to make it execute?

  2. robbieduncan Moderator emeritus


    Jul 24, 2002
    You can only use Objective-C in either pure Objective-C or Objective-C++ files. So .m or .mm files only. A cpp file will be treated as pure C++ and cannot, therefore, contain Objective-C syntax.
  3. gnasher729 macrumors P6


    Nov 25, 2005
    Objective-C++ is a superset of C++, just as Objective-C is a superset of C. In XCode, you could select the .cpp file, "Get Info" and change it from "C++ source file" to "Objective-C++ source file". It would be less confusing to the rest of the world if you just create a .mm file. In a .mm file, you can freely mix Objective-C and C++ code.
  4. imaxx thread starter macrumors newbie

    Aug 13, 2009
    I was thinking to split the .cpp file, by adding a function that calls the code in a .mm file. However, both will use the same file header for prototypes.
    This should add the needed clarity, i suppose.

    Would you think this solution would be deemed as 'appropriate'? Basically I make a c function with such code, and make the prototype available on the same .h file. The cpp file will call such function kept in the .mm file.

    I suppose this would work fine (.cpp calling .mm), am I wrong?

    Thanks for your answers, btw :)
  5. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Is there a need to use the cpp file elsewhere (in another project) that is C++-only? If not, why not just put everything into a .mm file and be done with it? Compiling something in Objective-C++ mode will do the right thing with plain C++. If you want to split things up for logical reasons, and not "language" reasons, that's perfectly fine, and using a header file for prototypes is the right thing to do. But even if you do divide them up, the cpp file can still be a mm file in case you wanted to add some Objective-C method invocations in the future, etc.

  6. imaxx thread starter macrumors newbie

    Aug 13, 2009
    well, it is part of a multi-platform code. Basically I need to compile it on various platforms.

    I could just keep it into a c++ file, and request the whole code to be added as Objc++, but probably if i split it up, it will be more clear to me, at least from a 'visual' standpoint in the project.

Share This Page