Mixing Objective-C and C++

Posted by helixed on Stack Overflow See other posts from Stack Overflow or by helixed
Published on 2010-04-26T00:21:35Z Indexed on 2012/07/01 15:16 UTC
Read the original article Hit count: 822

Filed under:
|
|

I'm trying to mix together some Objective-C code with C++. I've always heard it was possible, but I've never actually tried it before. When I try to compile the code, I get a bunch of errors. Here's a simple example I've created which illustrates my problems:

AView.h

#import <Cocoa/Cocoa.h>
#include "B.h"

@interface AView : NSView {
    B *b;
}

-(void) setB: (B *) theB;

@end

AView.m

#import "AView.h"

@implementation AView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
}

-(void) setB: (B *) theB {
    b = theB;
}

@end

B.h

#include <iostream>

class B {

    B() {
        std::cout << "Hello from C++";
    }

};

Here's the list of errors I get when I try to compile this:

/Users/helixed/Desktop/Example/B.h:1:0 /Users/helixed/Desktop/Example/B.h:1:20: error: iostream: No such file or directory


/Users/helixed/Desktop/Example/B.h:3:0 /Users/helixed/Desktop/Example/B.h:3: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'B'


/Users/helixed/Desktop/Example/AView.h:5:0 /Users/helixed/Desktop/Example/AView.h:5: error: expected specifier-qualifier-list before 'B'


/Users/helixed/Desktop/Example/AView.h:8:0 /Users/helixed/Desktop/Example/AView.h:8: error: expected ')' before 'B'


/Users/helixed/Desktop/Example/AView.m:26:0 /Users/helixed/Desktop/Example/AView.m:26: error: expected ')' before 'B'


/Users/helixed/Desktop/Example/AView.m:27:0 /Users/helixed/Desktop/Example/AView.m:27: error: 'b' undeclared (first use in this function)

All I'm doing to compile this right now is using the default compiler built into Xcode. I didn't edit the Cocoa Application template in any way other than adding the two files I created and chaing the NSView to AView in the xib file. Could somebody please tell me what I'm doing wrong?

Thanks,

helixed

© Stack Overflow or respective owner

Related posts about c++

Related posts about objective-c