3

I am trying to use some C++ classes in my Objective-C code for an iPhone application. I am just trying to declare the C++ object, and I am running into problems. Even though I am declaring the C++ header file in the Objective-C class I want to use it in, it does not appear that my Objective-C recognizes the C++ object. Here is my Objective-C code:

 //implementation file
#import "CPPClass.h"

@implementation MyViewController
- (void) viewDidLoad
{
    CPPClass object;
}

but I get an "Use of undeclared identifier 'CPPClass'" warning.

How am I supposed to do this?

coder
  • 10,172
  • 17
  • 67
  • 122
  • 3
    Did you change your .m file to a .mm file? – Richard J. Ross III Jan 16 '12 at 20:13
  • And, technically, you should #include C/C++ header files since some may actually rely on the difference in behaviour between #include and #import. Though you can be pretty certain that's making no difference here so this is in no way intended as an answer. – Tommy Jan 16 '12 at 20:16
  • @Tommy that is not the case, check out this question [here](http://stackoverflow.com/questions/439662) for clarification. Using #import increases performance, with no drawbacks. – Richard J. Ross III Jan 16 '12 at 20:20
  • @RichardJ.RossIII the two differ in behaviour or they wouldn't have added #import in the first place. So all C/C++ headers are written against the #include behaviour. See e.g. user512705's answer to the question you linked to for an example of where substituting #import for #include breaks a program. – Tommy Jan 16 '12 at 20:43
  • @Tommy no, you are missing the point. The only difference between #include and #import is that #import checks to see if the file has been included before, and if it has, it doesn't include it, reducing compile time, with no side-affects. – Richard J. Ross III Jan 16 '12 at 20:45
  • @RichardJ.RossIII see user512706's answer. Some standard GNU headers rely on being #included twice in the same source file (with enclosing #defines selecting relevant parts, but those are within another standard header). It's an edge case but a real one. Though I personally would avoid getting anywhere near that situation in anything I write like the plague. – Tommy Jan 16 '12 at 20:49

1 Answers1

4

If you want to use C++ code in Objective-C you need to have it in files with the .mm extension, which the compiler will interpret as Objective-C++ code. You also should #include C++ headers, not #import them.

DHamrick
  • 7,938
  • 9
  • 43
  • 58