Create and use static library on OS X

2019-04-11 17:21发布

问题:

OK, I'm trying to create a Cocoa Library (static) and use, but I keep getting errors.

I created a super-basic static Library (TSXLib) with just one additional class in it.

#import <Foundation/Foundation.h>

@interface ClassOne : NSObject

- (void)doIt;

@end

#import "ClassOne.h"

@implementation ClassOne

- (void)doIt
{
    NSLog(@"Oops... I did it again!");
}

@end

Then, I set the Dynamic Library Install Name (in Build Settings) to :

@executable_path/../Frameworks/libTSXLib.a

Now in my Test Project :

  • I drag'n'drop the libTSXLib.a file (and copied it to target)
  • Added a Build Phase (Copy Files) where I'm copying the libTSXLib.a to Frameworks
  • I'm then going to my AppDelegate.m and try importing my library's class
  • At #import <ClassOne.h>, the compiler throws an error that it can't find the class

Any ideas?


NOTE : I'm actually quite confused regarding libraries, frameworks, etc (that's why I tend to avoid them as much as possible). All I'm trying to do is pack some of classes/functions so that I can easily re-use them in different projects. Whether it is a framework, or a library, I really don't care. What I need is that : pack and re-use my code. (the ability to block anyone from seeing/using what's in, when bundled, would be a Plus)

回答1:

OK, so, coming back after some time, here's what I did to get it working :

Step 1 : Create the Library

  • Create a New Project, using the built-in Cocoa Library template
  • Set Library type as Static.
  • Add your Classes/Functions/Whatever
  • Under Build Phases, take care of which headers are going to go Public.

Step 2 : Use the Library in a test project

  • Drag’n'drop the final .a library file into the project (doesn’t matter if you also copy it to the target directory)
  • Link against the library
  • Update the User Header Search Paths to your initial Library .a file origin (using recursion (like /the/path/to/your/library/folder/**)
  • Set Always search user paths to YES
  • Add -ObjC to Other Linker Flags, under Build Settings.