How can I use C++ with Objective-C in XCode
Solution 1
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,
- Select your file.
- Open the File Info dialog (Cmd+I)
- In File Type, select "sourcecode.cpp.objcpp"
Solution 2
Rename the Objective-C file from filename.m
to filename.mm
to make it compile as Objective-C++.
Related videos on Youtube
prosseek
A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence
Updated on July 09, 2022Comments
-
prosseek almost 2 years
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?
-
Bruno Bieri almost 7 yearsMay this helps as well: stackoverflow.com/a/32546879/1306012 or philjordan.eu/article/mixing-objective-c-c++-and-objective-c++
-
-
Almas Adilbek over 9 yearsThank you man!! You helped me discover similar problem which took my two crazy days.
-
Pranav Kasetti about 5 yearsNow Xcode displays a more understandable suggestion Objectice-C++ Source