简体   繁体   中英

C++ and Objective-C

I need to use C++ file in my project, it's called CAXException.hpp , and row in project targets "Compile Sources As" - "According to file type" not Objective-C++. But when it's compiling it always displays me error error: expected '=', ',', ';', 'asm' or '__attribute__' before 'CAXException' in code:

class CAXException //<-------error here

{}

Please help me to fix it..

If I understand you correctly, you have a C++ header file ( .hpp ) that you want to include from Objective-C file. Unfortunately, you can't do that directly. You'll have to use a workaround.

The easiest is to change the compilation option of each and every Objective-C file ( .m ) that include this C++ header file (either directly or indirectly) to be compiled as an Objective-C++ file. This can be done either by renaming the files to .mm extension or by changing the option for the compiler for the file.

If this work for you, this will be the easiest, however Objective-C++ is not a complete superset of Objective-C (as C++ is not a superset of C), and some valid Objective-C is invalid Objective-C++ (if C++ keywords are used as variables names).

If this happens, you'll have to create an Objective-C wrapper to the class, with an implementation in Objective-C++ that simply delegate to the C++ class. That is create an CAXExceptionWrapper.h Objective-C file, containing something like:

@interface CAXExceptionWrapper {
  @private
    void* _CAXExceptionImpl;
}
- (id)init;
// ...
@end

And an `CAXExceptionWrapper.mm' Objective-C++ file containing:

@import "CAXException.hpp"
@implementation CAXExceptionWrapper
- (id)init {
    if ((self = [super init])) {
        _CAXException = new CAXExceptionWrapper;
    }
    return self;
}
// ...
@end

And then in your Objective-C files, include the wrapper Objective-C header instead of the C++ header.

class CAXException //<-------error here
{};
 ^^^

you are missing the ;

And Your compiler seems not to recognize the C++ keyword class , which is strange. Most likely, you are missing some ; before this class definition or some other syntax error but before this.

It is possible that that header is being included from an objective-c (.m extension) source code file. The source code file that includes that header must be an objective c++ one, ie ends with .mm or you can force objective c++ by explicitly changing the "Compile sources as..." setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM