22

I want to use/reuse C++ object with Objective-C. I have a hello.h that has the class definition, and hello.cpp for class implementation.

class Hello
{ int getX() ... };

And I use this class in Objective-C function.

#include "hello.h"
...
- (IBAction) adderTwo:(id)sender
{
    Hello *hi = new Hello();            
    int value = hi->getX();
    NSLog(@"Hello %d", value);
    [textField setIntValue:value];

When I compile the code in Xcode, I get this error message.

class Hello *XXXXX
Users/smcho/Desktop/cocoa/adderTwo/hello.h:9:0
/Users/smcho/Desktop/cocoa/adderTwo/hello.h:9: 
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Hello'

What went wrong?

prosseek
  • 155,475
  • 189
  • 518
  • 818
  • May this helps as well: https://stackoverflow.com/a/32546879/1306012 or http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++ – Bruno Bieri May 24 '17 at 08:01

2 Answers2

34

Make sure you compile that file as "Objective-C++".

The simplest way is to rename it as *.mm.

If you don't want to rename the *.m file,

  1. Select your file.
  2. Open the File Info dialog (Cmd+I)
  3. In File Type, select "sourcecode.cpp.objcpp"
kennytm
  • 469,458
  • 94
  • 1,022
  • 977
7

Rename the Objective-C file from filename.m to filename.mm to make it compile as Objective-C++.

Marcelo Cantos
  • 167,268
  • 37
  • 309
  • 353