在Xcode中使用C++与Objective-C混编

时间:2022-09-07 07:38:25

有时候,出于性能或可移植性的考虑,需要在iOS项目中使用到C++。

假设我们用C++写了下面的People类:

//
// People.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//

#ifndef __MixedWithCppDemo__People__
#define __MixedWithCppDemo__People__

#include <iostream>

class People
{
public:
void say(const char *words);
};

#endif /* defined(__MixedWithCppDemo__People__) */

////  People.cpp//  MixedWithCppDemo////  Created by Jason Lee on 12-8-18.//  Copyright (c) 2012年 Jason Lee. All rights reserved.//#include "People.h"void People::say(const char *words){    std::cout << words << std::endl;}

然后,我们用Objective-C封装一下,这时候文件后缀需要为.mm,以告诉编译器这是和C++混编的代码:

//
// PeopleWrapper.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//

#import <Foundation/Foundation.h>
#include "People.h"

@interface PeopleWrapper : NSObject
{
People *people;
}

- (void)say:(NSString *)words;

@end

////  PeopleWrapper.mm//  MixedWithCppDemo////  Created by Jason Lee on 12-8-18.//  Copyright (c) 2012年 Jason Lee. All rights reserved.//#import "PeopleWrapper.h"@implementation PeopleWrapper- (void)say:(NSString *)words{    people->say([words UTF8String]);}@end

最后,我们需要在ViewController.m文件中使用PeopleWrapper:

    PeopleWrapper *people = [[PeopleWrapper alloc] init];
[people say:@"Hello, Cpp.\n"];
[people release], people = nil;

结果发现编译通不过,提示“iostream file not found”之类的错误。

这是由于ViewController.m实际上也用到了C++代码,同样需要改后缀名为.mm。

修改后缀名后编译通过,可以看到输出“

Hello, Cpp.

”。