Creating Static Libraries For iOS

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
April 7th, 2011 Posted by: (ELC) - posted under:Tutorials

Today I’m going to show you how to make a static library for iOS. We will make a simple library and use it in a separate project.

What’s a static library

Here is what wiki has to say:

In computer science, a static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable. This executable and the process of compiling it are both known as a static build of the program. Historically, libraries could only be static.

On the iPhone, static libraries have a .a extention and can only contain code. This means that any resources (xibs, images, etc…) must be packed either in a bundle or shipped separately than the library. We won’t go into this part today.

Why Use Static Libraries

There are a number of reasons to use static libraries, but the main two are distribution to others without revealing source code, and code reuse across projects.

1. Distribution:

Say you have a great idea for a view that given a few images, creates a beautiful photo mosaic. Now, others might want to use your awesome mosaic class as part of their fart-light (fart machine flashlight) app to make mosaic fart-lights from your photo library. You have done a ton of work to make your mosaic app and don’t want to just give away the code. $$$ you decide to sell your code. However, would-be thieves might not honor your awesome license and begin to redistribute the code as if it were their own (oh noooz). Boom static library.

Bundle up your code into a static library and package it with the header files. Now others can purchase your library, use it in their own apps to make fart mosaics without revealing the source and you can continue to sell copy after copy.

2. Code reuse:

So, you have like 30 apps in the store that do just about nothing. However they all have some common code, say a farting engine. Rather than dragging all of the source files in and having redundant code all over the place, you can just compile your fart engine once and use the library in all of your projects.

Where Can I Get Me One Of These?

Well, let’s dig in and create a sample static library. The project we are going to create is code-only (remember we are not going over resources in this tutorial) and will be a simple math library with two methods exposed. It will be able to compute fibonacci numbers given number n and compute a factorial value given number n (I know, pretty dang exciting).

Step 1: Starting a New Static Library Project

This is pretty straight forward as Apple has made it pretty simple to create a static library.

Open XCode and start a new project. Under iOS, select Library and “Cocoa Touch Static Library”. We are going to name ours ICodeMathUtils. This will create a nice new project for us that builds a .a file.

One thing to note is, NO class files get created by default. Don’t freak out, we will create some manually.

Step 2: Code your static library

First we need to add some files. Add a new NSObject subclass to your project and name it MathFunctions.m.

Add this code to the header file:

#import 
 
@interface MathFunctions : NSObject {
}
 
- (NSArray *) fibonacci:(NSInteger) n;
- (NSInteger) factorial:(NSInteger) n;
 
@end

Nothing fancy, just our method declarations. When we distribute the library file, this header file MUST be included as well.

One thing I should point out here is don’t make every iVar public! As a newer developer (or a stubborn lazy one: Im looking at you @cruffenach), you might think it’s cool to make a public property out of EVERYTHING. This is bad form and here is where it will bite you. You don’t want the external world being able to muck with things that you don’t want them to.

And Now the .m file for the implementation:

#import "MathFunctions.h"
 
@implementation MathFunctions
 
- (NSArray *) fibonacci:(NSInteger) n {
 
	NSMutableArray *fib = [NSMutableArray array];
 
	int a = 0;
	int b = 1;
	int sum;
	int i;
 
	for (i=0;i < n;i++)
	{
		[fib addObject:[NSNumber numberWithInt:a]];
		sum = a + b;
		a = b;
		b = sum;
	}
 
	return (NSArray *) fib;
}
 
- (NSInteger) factorial:(NSInteger) n {
	if ( n <= 1 )
		return 1;
	else
		return n * [self factorial:( n-1 )];
}
@end

This code should be very familiar to any CS 101 student : ). And that’s it for our static library. The best way to test this puppy out before distributing is to create a new unit test target, set up some unit tests, and check it out that way. That tutorial is for another day.

Building And Distributing Your Library

Once you are happy with your library, simply build it in XCode. Obviously, don’t do build and run as you can’t run it (again unless you have a test suite). Now, look under the Products group in XCode and you should see a file called lib(libraryName).a. In our case, it’s libICodeMathUtils.a.

Right click on that file and select “Reveal In Finder”. Drag this file into a new folder that you create where you will be bundling all of your library files. I just created a folder on my desktop named iCodeBlogsMathLibrary. Now, do the same with all of the .h files. In our case, just copy MathFunctions.h into this new directory. Your directory structure should now look like:

iCodeBlogsMathLibarby
|- libICodeMathUtils.a
|- MathFunctions.h

Now you can zip this folder and sell it to would-be iOS developers for millions!

Linking Your Library In A New Project

So now that you have built your shiny new static library, it’s time to test it out in another application. XCode has a number of ways to actually achieve this, but I will show the most simple and Mac-like… drag and drop : ).

Create a new View-Based project (or whatever it doesn’t really matter). I named mine MathTest.

Now, just drag this folder into the project and XCode will set up all of the linking automagically. When prompted to copy, I usually say yes, but you can do whatever you want depending on how you intend on using the library. Sometimes just linking and not copying is far more beneficial if you have multiple projects sharing a single library. It ensures that they all use the most up to date version.

You should now see the .a file along with the header files in the new project.

Using The Static Library Code

Now that all of the linking is set up, you just use your library like any other class. In the App Delegate class of my test project, I simple did this:

// Import at the top
#import "MathFunctions.h"

And in the applicationDidFinishLaunchingMethod…

MathFunctions *mFunctions = [[[MathFunctions alloc] init] autorelease];
NSLog(@"fibonacci for 10 = %@", [mFunctions fibonacci:10]);
NSLog(@"10! = %d",[mFunctions factorial:10]);

This of course prints out:

2011-04-07 11:48:49.528 MathTest[854:607] fibonacci for 10 = (
    0,
    1,
    1,
    2,
    3,
    5,
    8,
    13,
    21,
    34
)
2011-04-07 11:48:49.533 MathTest[854:607] 10! = 3628800

And there it is! Static library code being executed in a totally separate project.

Conclusion

Like I said earlier, static libraries can be quite helpful in your iPhone development endeavors. I feel that they are quite underused, but could really save time and money in the long run.

You can download the source code here.

As always, if you have any questions please feel free to leave them in the comments OR write me on Twitter.

Happy iCoding!

  • Anonymous

    Great overview. I appreciated the simplicity of how to create the static library – and was even more impressed by how easily Xcode can work with it. This gives me some great ideas for my own coding…can’t wait to dig in!

  • Stefan

    Great tutorial, thank you! One question, though: why didn’t you implement the two methods as class methods? Is there a specific reason?

  • Alejandro

    Great tutorial..very useful for next projects..thanks.
    i have some problem when Build MathTest in Xcode 4…it gives me this error:
    …iCodeBlogsMathLibrary/libICodeMathUtils.a, missing required architecture i386 in file
    do you know how to fix it ?

  • Anonymous

    I’m not sure what you mean. I implemented both methods inside of MathFunctions.m. They both match the method signature found in the .h file.

  • Anonymous

    hrm…. yeah XCode 4 is a little different when linking in static libraries. I’ll update this to include it. For the time being, try clicking on your project -> Build Phases -> drag the .a file in to the Linked Libraries build phase. Let me know if that works.

    OR

    That message might mean that you build the library for the device and tried to link it with the simulator or vice versa.

  • Anonymous

    Ahh (facepalm), I’m a space cadet. Didn’t put that together. I didn’t make them class methods for demo purposes. I guess I could have, but there’s no specific need to.

  • Alejandro

    ..no, a. file is already linked and i get the same problem..i’ve built with iOS device
    second option…i’cant buid for Base SDK Mac OSX because don’t have certificate..
    thanks anyway

  • http://alltom.com/ Tom

    “Now others can purchase your library, use it in their own apps to make fart mosaics without revealing the source and you can continue to sell copy after copy.”

    Why wouldn’t the thieves just redistribute the static library? O.o

  • Léo
  • Anonymous

    I guess they could, by why would they want to?

    1. No updates
    2. No ability change
    3. Easily detectable as they won’t just be “merging” your code with their own.
    4. Perhaps you just don’t want to reveal the inner workings of your code, connection endpoints, etc… (static libs that do this include FBConnect, Google Analytics, AdMob, etc…)

    Piracy is always going to exist. This is just one step in the right direction for combatting it.

  • http://profiles.google.com/louisp.tremblay Louis-Philippe Tremblay

    Thanks for the heads up, i was starting to wonder if it was even possible to do, since there are so little good commercial libraries available (at least compared to windows development)

    So if we compile a library using say sdk 4.2, can people link against it and build in 4.3?

    Also, are you aware if it would that be an issue for App store review that Apple cannot view the source code?

  • Brian

    Thanks for the article. Also I didn’t know, from the comments below, building a static libary, one would have to build for the device, and similulator. Also, one would have to do debug and release builds. So, four builds in total. Again, thanks for the article.

  • Susim1985

    I am getting red in my libICodeMathUtils.a file.How I can I remove this.

  • Susim1985

    I am getting red in my libICodeMathUtils.a file.How I can I remove this.

  • Anonymous

    1. Yes

    2. Apple can’t view your source code when you compile a .app file. So, no it shouldn’t be a problem at all. That would be pretty crazy if you had to submit your source. I think it would change things quite a bit ;)

  • Anonymous

    That’s correct. I need to be more clear about that in the post. I’ll update it to show how you go about doing that. Thanks for pointing that out.

  • Anonymous

    Is this in your library project or the sample project that uses the library?

  • Monclerjacketsdx454gvcxb3

    White color is pretty appreciably synonymous with pearls but they do arrive in other eye-catching colours just like black, pink, lavender, http://www.shopslimming.com/p57-hoodia/p57-hoodia-slimming/15-boxes-p57-hoodia-slimming-capsules.html golden and gray etc. There are 4 types of pearls plus they are freshwater, Akoya seawater, Tahitian and South seawater ones. Freshwater and akoya market extra than other styles usually for their reduce expenses and color brilliance.

  • Matter

    Hi thank you for this post!
    I have a doubt about your final .a output.
    Here you obtain only one file (i presume thus that you create a version for simulator only) if i need to use this lib on a device it doesn’t work. I’m in wrong ?

  • Vasudha

    When I am importing MathFunctions.h in my App Delegate I am getting 33049 error all because the MathFunctions.h contains all the symbols and no code is visible there. Please help. Thanks in advance.

  • Vasudha

    When I compiled the code following is tge error I am getting:

    “_OBJC_CLASS_$_MathFunctions”, referenced from:
    objc-class-ref-to-MathFunctions in MathTestAppDelegate.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    Can any one help me ?
    Thanks in advance.

  • Vasudha

    When I compiled the code following is the error I am getting:

    “_OBJC_CLASS_$_MathFunctions”, referenced from:
    objc-class-ref-to-MathFunctions in MathTestAppDelegate.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    Can any one help me ?
    Thanks in advance.

  • http://twitter.com/thecoleorton Cole Orton

    per your #1 and #2 points above, can you override classes in a static library? if not, what would you suggest for a code reusability that allowed for slight tweaks to the .m files? or being able to override a class?

    thanks in advance!

  • kA

    Vasudha, You need to compile as a device, as it seams this example is being created just for device, an another static library with simulator should be created and then added as one universal fat file, but perhaps that’s something you can do from your behalf too, if the steps have been provided. My concern here comes as using static library vs framework, as the resource can be dynamically loaded, so this is something I am challenging myself and the group to see if this is a good proof of concept.

    So here is my scenario: I have some pre-defined classes from Unity, which I am thinking of getting bundled within static library so I don’t have to keep adding into the project, however this has become a major issue as Unity is also utilizing their own library, so a tree of dependencies is what I am looking into, which is highly restricted via apple.

    Unless if someone can give me some right directions here as of how to bundle bunch of .dll.s files, .app files, headers and .m files within a static library, as most example I have seen is just utilizing easy couple of class file. Also, there is one library provided by unity, so I was just curious is it possible to link binary library within static library? if so, is there any good example as of how to do so?

    Thanks.

    kA

  • Anonymous

     Thanks for sharing complete post with source code. I would like to appreciate your hard work. Good on you.iphone developer

  • http://jinibot.com iPhone Consultants

    Static L

  • iphone app design

    Nice post! The source code is really of great help for many. But importing  MathFunctions.h is a troublesome task for me.Its taking more time than i expected.

  • Renuga

    Hi brandontreb,

    Thanks for sharing complete post with source code. I would like to appreciate your hard work.

    It’s working good in simulator.But, tried build for a device it’s show me an error.could you please help me.

    please tell me the procedure to port the application(i’m creating one separate application using static Library classess)

    Thank You brandontreb :)

  • Trwww

    Hi Stefan, could you explain what would need changed so that the methods would be class methods? And maybe what the code would look like in the consumer if they were? Just getting started here so just learning this stuff…

  • Nhattruong

     I think so
    ————
    Khuyen mai

  • http://twitter.com/blackliteon blackliteon

    Thank you for article.

    Take a look at this guide about using static libraries with projects in one workspace for Xcode 4 : https://docs.google.com/document/pub?id=14XR5zcZb2Kz2s6A4AbzB00NLkrW9bWxMMprVsUao-hY

  • Anonymous

    sounds great…
    so I will have a try about it…

  • Uranazo

    This should be class methods not instance methods.

    + (NSInteger) factorial:(NSInteger) nThat way you don’t have to create a math object which takes no data other than that through the parameters… By making all methods class methods they are now similar to a static class in Java.

  • Developer

    Thanks, your post is really helpful.

    I know that your post is mainly technical, but I do have a question from a different aspect.

    I would like to build a static library, and i want to guaranty to my clients that my static library won’t fail the approval of their app. 
    Is there anyway to get approval for static library from Apple?
    Or my only option is to make my own app that uses my static library, and to submit my app to the app store?

    Thanks.

  • Anonymous

    Fantastic sharing! That’s what I’m looking for!

  • Neel4r

    how to customize the  stand UItextfield include handling of the delegates of the textfield

  • http://www.prrankchecker.com/ pr check

    A probability is expressed as a numeric value between 0 and 1. A 0.5
    probability is commonly expressed as a “50% chance” of something
    happening. Hence, a PageRank of 0.5 means there is a 50% chance that a
    person clicking on a random link will be directed to the document with
    the 0.5 PageRank.

blog comments powered by Disqus
canakkale canakkale canakkale balik tutma search canakkale vergi mevzuati