Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build library written by C++ and use in iOS

I now have to porting C++ code to iOS, trying to build static library by original C++ code and load the library on iOS. Because the original code is heavy, I start a small test to verify my steps could work or not.

First I need to build library (.a), which prints some string. I compile the following code and generate a library(.a) file

//talk.h
...
#include <iostream>
class Talk {
    Talk();
    void printHello();
    void printWord(char*);
};


//talk.cpp
#include "talk.h"
using namespace std;
void Talk::printHello() {
    cout << "Hello World";
}
void Talk::printWord(char* word) {
    cout << "Hello" << word;
}

The second step I try to do is open a new project for iOS app and then set link to the library file, also include corresponding "talk.h" header file. However, some errors happen on the header file even though I build library successfully.

The errors indicate that

  1. "iostream" file not found
  2. "Unknown type name 'class'; did you mean 'Class'?
  3. any other errors...

I have try to rename controller.m to controller.mm, but it not fixes the problem

How to import the header file written in C++ for using library on iOS? Thanks

like image 858
Kuan-Jong Wu Avatar asked Oct 23 '13 02:10

Kuan-Jong Wu


1 Answers

A rough outline:

In Xcode (starting with an either one of the template iOS Application projects (or an existing one):

  • Create a new static library target: File -> New -> Target.... Select Framework Or Library, and then Cocoa Touch Static Library
  • Add library source code: Drag library source code into Xcode project. In the dialog that appears, select the build target created above.
  • Add project dependancy to library: Select Project in Project Navigation, the the iOS build target from Targets. Select Build Phases tab, then under Target Dependancies in the window, click on the + sign. A sheet opens (choose items to add) and the library target should be at thee top of the list.
  • Include Library in iOS Target: Under Link Binary with Libraries, click +. The library (a .a file) should be at the top of the list.
  • Link with libc++: As the step above. Select libc++ from the list.
  • Enable Objective-C++ compilation for any source code file that needs to include the library headers by changing the extension from .m to .mm
  • Build the iOS application target.

Xcode will have taken care of setting everything else up for you, including compiler flags and header search paths.

like image 54
marko Avatar answered Oct 17 '22 01:10

marko