问题
I had a trouble to combine c++ and objective-c together in developing a iphone app. I had a 3rd party library to use in the app. I had a plan to use c or c++ to wrap the library and then use objective-c to call it. After I had finished the class with c++, I had a trouble to use it in objective-c. Is there any sample code? Thanks.
in the objective-c head file. I write
#import <UIKit/UIKit.h>
#import "ZJTConstants.h"
#include "TTSAdapter.h"
class Adapter;
@interface ZJTVBlogViewController : UIViewController {
@private
Adapter* adapter;
}
@end
and in the mm file, I write:
if (self) {
adapter = Adapter::getInstance();
// Custom initialization
}
Is it write?
回答1:
Calling C++ code from Objective-C code involves ending your file with .mm (instead of .m) so that the Objective-C++ compiler will be used.
This compiler can understand both C++ and Objective-C.
In other words, the ObjC++ compiler lets you put C++ code directly in Objective-C methods, and vice versa.
Take a look at Cocoa_With_Carbon_or_CPP example and Strategies for Using C++ in Objective-C Projects (and vice versa) article .
回答2:
In XCode there is a flag to compile all files as Objective-C++. I've used it to compile huge C++ libraries into iOS programs.
If you look at the "Build Settings" there is a place written "Compile Sources As". There is a dropdown menu there where you can select Objective-C++. In the clang/gcc commandline I think it is "-x objective-c++".
回答3:
Just rename your file to have an extension .mm
instead of .m
.
To mix C++ code with Objective-C code, you will need Objective-C++ compiler.
XCode by default compiles .m
files with Objective-C compiler and .mm
ones with Objective-C++ one.
来源:https://stackoverflow.com/questions/9250655/how-to-use-c-and-objective-c-together-in-xcode-4-2