这几天的工作挖了不少的坑,遇到了各种千奇百怪的错误,现在好好总结一下。
新建一个工程,然后新建HelloCPP.h,HelloCPP.cpp文件,HelloCPP.h文件内容如下:
#ifndef __CPPWrong__HelloCPP__
#define __CPPWrong__HelloCPP__
//#include <stdio.h>
namespace hello
{
};
#endif /* defined(__CPPWrong__HelloCPP__)
就一个空的namespace。
然后在ViewController.m中导入HelloCPP.h,如下:
#import "ViewController.h"
// 导入C++头文件
#import "HelloCPP.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
接着Run,报错,提示如下:
被导入的C++头文件无法识别其命名空间。
解决方法:
通常在工程中,如果遇到在OC中使用C++代码运行异常的问题,是因为其中的C++头文件被一个OC .m文件引用了。为了实现OC和C++混编,必须要将引用的.m文件后缀修改为.mm。