如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:20:30  来源:igfitidea点击:

How can I use C++ with Objective-C in XCode

c++objective-cxcodeobjective-c++

提问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 文件,

  1. Select your file.
  2. Open the File Info dialog (Cmd+I)
  3. In File Type, select "sourcecode.cpp.objcpp"
  1. 选择您的文件。
  2. 打开文件信息对话框 (Cmd+I)
  3. 在文件类型中,选择“sourcecode.cpp.objcpp”

回答by Marcelo Cantos

Rename the Objective-C file from filename.mto filename.mmto make it compile as Objective-C++.

将 Objective-C 文件从 重命名filename.mfilename.mm以使其编译为 Objective-C++。