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

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

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

  1. //
  2. // People.h
  3. // MixedWithCppDemo
  4. //
  5. // Created by Jason Lee on 12-8-18.
  6. // Copyright (c) 2012年 Jason Lee. All rights reserved.
  7. //
  8. #ifndef __MixedWithCppDemo__People__
  9. #define __MixedWithCppDemo__People__
  10. #include <iostream>
  11. class People
  12. {
  13. public:
  14. void say(const char *words);
  15. };
  16. #endif /* defined(__MixedWithCppDemo__People__) */
  1. //
  2. // People.cpp
  3. // MixedWithCppDemo
  4. //
  5. // Created by Jason Lee on 12-8-18.
  6. // Copyright (c) 2012年 Jason Lee. All rights reserved.
  7. //
  8. #include "People.h"
  9. void People::say(const char *words)
  10. {
  11. std::cout << words << std::endl;
  12. }

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

  1. //
  2. // PeopleWrapper.h
  3. // MixedWithCppDemo
  4. //
  5. // Created by Jason Lee on 12-8-18.
  6. // Copyright (c) 2012年 Jason Lee. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. #include "People.h"
  10. @interface PeopleWrapper : NSObject
  11. {
  12. People *people;
  13. }
  14. - (void)say:(NSString *)words;
  15. @end
  1. //
  2. // PeopleWrapper.mm
  3. // MixedWithCppDemo
  4. //
  5. // Created by Jason Lee on 12-8-18.
  6. // Copyright (c) 2012年 Jason Lee. All rights reserved.
  7. //
  8. #import "PeopleWrapper.h"
  9. @implementation PeopleWrapper
  10. - (void)say:(NSString *)words
  11. {
  12. people->say([words UTF8String]);
  13. }
  14. @end

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

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

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

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

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

Hello, Cpp.

”。

版权声明:本文为博主原创文章,未经博主允许不得转载。