How to deal with forward declaration / #import in Cocoa Touch (Objective-C cross C++) correctly?

unknownthreat picture unknownthreat · Jul 22, 2009 · Viewed 11.2k times · Source

I am trying to write this header file:

//@class AQPlayer;

//#import "AQPlayer.h"

@interface AQ_PWN_iPhoneViewController : UIViewController {

    AQPlayer* player;
}

@end

AQPlayer is a .mm file written in C++.

I tried to make a class forward declaration here, but it complains to me:

error: cannot find interface declaration for 'AQPlayer'

So I tried to "#import" the header file instead, but it complains something completely off and weird. Here's a slice of the error complained:

In file included from

/Users/akaraphan/Desktop/SpecialTopic1/AQ_PWN_iPhone/Classes/AQPlayer.h:51,
                 from /Users/akaraphan/Desktop/SpecialTopic1/AQ_PWN_iPhone/Classes/AQ_PWN_iPhoneViewController.h:12,
                 from /Users/akaraphan/Desktop/SpecialTopic1/AQ_PWN_iPhone/Classes/AQ_PWN_iPhoneAppDelegate.m:10:
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:78: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'CAStreamBasicDescription'
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:230: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:231: error: expected '=', ',', ';', 'asm' or '__attribute__' before '==' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:233: error: expected '=', ',', ';', 'asm' or '__attribute__' before '!=' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:234: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<=' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:235: error: expected '=', ',', ';', 'asm' or '__attribute__' before '>=' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:236: error: expected '=', ',', ';', 'asm' or '__attribute__' before '>' token
/Developer/Examples/CoreAudio/PublicUtility/CAStreamBasicDescription.h:239: error: expected ';', ',' or ')' before '&' token

Am I missing something? Can't I do a forward declaration for this?

Answer

Daniel Dickison picture Daniel Dickison · Jul 22, 2009

The normal way to do this would be:

// In your .h file...
@class AQPlayer;
@interface AQ_PWN_iPhoneViewController : UIViewController {
    AQPlayer *player;
}
@end

// In your .mm file (see below why it has to be .mm instead of .m)...
#import "AQ_PWN_iPhoneViewController.h"
#import "AQPlayer.h"
@implementation AQ_PWN_iPhoneViewController
...
@end

The heavy duty errors you see is probably because the compiler is trying to parse AQPlayer.h as Objective-C instead of Objective-C++. You'll probably have to use .mm for all of your source files that imports AQPlayer, even if that particular class doesn't use C++.