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?

6
  • 3
    Did you change your .m file to a .mm file? Commented Jan 16, 2012 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. Commented Jan 16, 2012 at 20:16
  • @Tommy that is not the case, check out this question here for clarification. Using #import increases performance, with no drawbacks. Commented Jan 16, 2012 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. Commented Jan 16, 2012 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. Commented Jan 16, 2012 at 20:45

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

#include vs #import means nothing really. You can do either. #import only checks to see if you haven't included the file already
And, rather than changing to .mm, you can set the Objective-C++ file type in the file attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.