.m文件导入C++头文件带来的错误

这几天的工作挖了不少的坑。遇到了各种千奇百怪的错误,如今好好总结一下。

新建一个project,然后新建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++头文件无法识别其命名空间。


解决方法:

通常在project中,假设遇到在OC中使用C++代码执行异常的问题,是由于当中的C++头文件被一个OC .m文件引用了。为了实现OC和C++混编,必需要将引用的.m文件后缀改动为.mm



原文地址:https://www.cnblogs.com/liguangsunls/p/7220859.html