混合Objective-C和C++时,未知类型名称'class'

Mer*_*ede 4 objective-c objective-c++

这真让我抓狂.

我在foo.h文件中有一个C++类声明.

class foo // error marks are here
{
};
Run Code Online (Sandbox Code Playgroud)

当我#include/#import在我的fooUser.mm文件中的这个标题时,它编译.当我#include/#import在我的fooUser.h文件中执行它时,它没有,并且编译器错误是.

Unknown type name 'class'; did you mean 'Class'?
Excpected ';' after top level declarator.
Run Code Online (Sandbox Code Playgroud)

我正在使用XCode 4.2,LLVM编译器3.0,......这应该是重要的.

Mar*_*n R 7

正如您在评论中所说,"fooUser.h"也包含在非C++文件中,这会导致编译器错误.头文件不是单独编译的,而是作为包含它们的"编译单元"的一部分编译的.

您应该尝试将C++声明分离为仅包含在(Objective-)C++文件中的头文件.

作为一种解决方法,您还可以通过以下方式保护C++声明

#ifdef __cplusplus
// …
#endif
Run Code Online (Sandbox Code Playgroud)