简体   繁体   中英

Import .CPP files from a working iOS project and rename to .mm issue

I have copied a .CPP and its .h file from a working project to a new one.

I renamed the ending from .CPP to .mm but it still gives me errors.

In the .h file, near the class definition class MeterTable , it says it expect the ;

In the .mm file, there are all kinds of errors.

I thought by changing the ending of the implementation file .mm it would clean all those errors. And yes, the original .CPP file compiled under the old project.

Looks like you're including that .h file into some other .m file. You cannot just include C++ header into a C or Objective-C source file. You need to make sure that your C++ interface is C compatible (no classes, only free functions without overloading). Or you would have to change all your .m files in the project into .mm .

The only solution is to have an inline header file.

Change your .h file to .hpp and combine your .cpp file with your .h file.

As example; your .h file:

// class.h

class {
public:
    void someclass(int a);
};

And your .cpp file:

// class.cpp

#include "class.h"

void someclass(int a) {
    return;
}

Merge into .hpp like this:

// class.hpp

class {
public:
    void someclass(int a) {
        return;
    }
};

Objective-C and C++ can play nicely together, but there are a couple of caveats. First, any .m file that references C++ code (ie, via a header) must be defined to be an Objective-C++ source, not Objective-C. This can be done on a case-by-case basis by going to the File Inspector for the .m file and changing the file type from Objective-C Source to Objective-C++ source. Second, use the same method to define the .h and .cpp (or .mm , the actual extension does not really matter, it's the defined types) as C++ Header and Objective-C++ source, respectively.

As long as you use this compartmentalization of file types, you should be able to mix Objective-C and C++ freely -- I commonly use this paradigm to consume C++ in my iOS code.

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