如何在 XCode 中使用 C++ 和 Objective-C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2683101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use C++ with Objective-C in XCode
提问by prosseek
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.
我想在 Objective-C 中使用/重用 C++ 对象。我有一个具有类定义的 hello.h 和用于类实现的 hello.cpp。
class Hello
{ int getX() ... };
And I use this class in Objective-C function.
我在 Objective-C 函数中使用了这个类。
#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.
当我在 Xcode 中编译代码时,我收到此错误消息。
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?
什么地方出了错?
回答by kennytm
Make sure you compile that file as "Objective-C++".
确保将该文件编译为“Objective-C++”。
The simplest way is to rename it as *.mm.
最简单的方法是将其重命名为*.mm。
If you don't want to rename the *.m file,
如果您不想重命名 *.m 文件,
- Select your file.
- Open the File Info dialog (Cmd+I)
- In File Type, select "sourcecode.cpp.objcpp"
- 选择您的文件。
- 打开文件信息对话框 (Cmd+I)
- 在文件类型中,选择“sourcecode.cpp.objcpp”
回答by Marcelo Cantos
Rename the Objective-C file from filename.m
to filename.mm
to make it compile as Objective-C++.
将 Objective-C 文件从 重命名filename.m
为filename.mm
以使其编译为 Objective-C++。