HowTo compile native C codes to a library for iOS development in Xcode – take Mosquitto as an example

For iOS development, sometimes you want to use a existed native C codes for help. Objective-C is a superset of C so it’s easy to combine C codes in your Objective-C project. But for a library usage, it only support compiling C code to a static library by now.

In this tutorial, I take an open source project MQTT message broker Mosquitto as an example to demo how to compile it into a static library in Xcode.

Environments
* Xcode 4.1
* MacOSX Lion
* mosquitto 0.13

Tutorial
1. Download mosquito form <http://mosquitto.org/files/source/mosquitto-0.13.tar.gz>. Here is the whole directory structure:

wpid-wpid-Voila_Capture58-2011-10-30-10-483-2011-10-30-10-483.png

2. Create a new project by template C/C++ Library
* Choose static type

wpid-wpid-Voila_Capture60-2011-10-30-10-483-2011-10-30-10-483.png

wpid-wpid-Voila_Capture61-2011-10-30-10-483-2011-10-30-10-483.png

3. Import(or just drap and drop) C codes(include .h and .c) to the project

wpid-wpid-Voila_Capture63-2011-10-30-10-483-2011-10-30-10-483.png wpid-wpid-Voila_Capture64-2011-10-30-10-483-2011-10-30-10-483.png

4. Check the “Build settings” in project

* “Base SDK” => Latest iOS
* “Architectures” => Standard(armv6 armv7)
* “Supported Platforms” should include “iphonesimulator iphoneos”

wpid-wpid-Voila_Capture72-2011-10-30-10-483-2011-10-30-10-483.png

5. Check the “Build Phases” in targets
* “Copy Headers” => Add or move(from “Project”) the header files that should be referenced to “Public”

wpid-wpid-Voila_Capture65-2011-10-30-10-483-2011-10-30-10-483.png

6. Select Scheme respectively for iOS Device and iPhone/iPad Simulator for Build(Cmd+b) and resolve the errors

* Select iOS Device will make product(.a) in …<Debug/Release>-iphoneos
* Select iPhone/iPad simulator will make product(.a) in …<Debug/Release>-iphonesimulator

wpid-wpid-Voila_Capture66-2011-10-30-10-483-2011-10-30-10-483.png wpid-wpid-Voila_Capture76-2011-10-30-10-483-2011-10-30-10-483.png

* Right-click the product name and click “Show in Finder” to locate files
wpid-wpid-Voila_Capture71-2011-10-30-10-483-2011-10-30-10-483.png wpid-wpid-Voila_Capture89-2011-10-30-10-483-2011-10-30-10-483.png

7. Now you can copy the public header files and static library to the next project you want to use it.
wpid-wpid-Voila_Capture79-2011-10-30-10-483-2011-10-30-10-483.png

Notes:

1. Only static library(product will be the .a format) support for iOS

2. The compiled library for simulator and physic device is different

Posted in Programming. Tags: , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>