close

引用網址:http://www.jianshu.com/p/486e3b737707

Xcode Version: 8.0 beta
iOS SDK Version: iOS 10

Step 1: 建立工程

创建工程时选择Cocoa Touch Static Library.

创建工程时选择Cocoa Touch Static Library

工程名设置为:HelloWorld

设置工程名


工程结构如下:

工程结构


Note: libHelloWorld.a为输出的静态库文件,编译前为红色,编译后为黑色.

Step 2:函数定义和实现

HelloWorld.h中

@interface HelloWorld : NSObject

+ (void)say;

@end

HelloWorld.cpp中

@implementation HelloWorld

+ (void)say
{
    NSLog(@"Hello World!");
}

@end

Step 3:设置Run Scheme为Release

  • Edit Scheme
Edit Scheme
  • 选择Run Scheme时的Build ConfigurationRelease(默认为Debug).
    Run Scheme设置为Release
  • 编译并查看结果.
    此时分别选择iPhone 6 Plus(模拟器中随意选一款即可)和Generic iOS Device(或直接选择真机)进行编译。
Paste_Image.png


运行后,选中libHelloWorld.a点击右键, 选择Show in Finder:

Paste_Image.png


可看到编译结果分别置于:
Release-iphonesimulator(simulator的编译结果)和Release-iphoneos(Generic iOS Device的编译结果)中

Paste_Image.png


其中libHelloWorld.a是输出的静态库文件, 而include中为需要的头文件.

Step 4: 合并静态库文件

Release-iphonesimulator中的库文件仅支持在simulator下使用
在命令行中,切换到该目录下,查看其相关信息:

Paste_Image.png

看出其支持i386和x86_64两种架构.

Release-iphoneos仅支持在真机下使用.
查看其相关信息:

Paste_Image.png

看出其支持armv7和arm64两种架构.

如果我们打算在simulator和真机下同时使用,应该合并上述两个文件.
切换到Release-iphonesimulatorRelease-iphoneos的同级目录, 执行合并命令:

lipo -create Release-iphonesimulator/libHelloWorld.a Release-iphoneos/libHelloWorld.a -output libHelloWorld.a

可以看到目录下生成了一个新的文libHelloWorld.a:

Paste_Image.png


查看该文件的信息:

Paste_Image.png


可以看出目前的库文件支持i386 armv7 x86_64 arm64四种架构,支持在simulator和真机上同时使用.

Step 5: 使用静态库文件

创建一个新的Xcode的工程, 工程名为CallLibDemo, 工程类型选择Single View Application.
拷贝Step 4生成的libHelloWorld.aRelease-iphoneosinclude目录中的文件到工程中.
并将文件添加到工程中.

Paste_Image.png

导入后目录结构如下:

Paste_Image.png


Note: 此时工程的Build PhasesLink Binary With Library会默认添加libHelloWorld.a

ViewContorller.m中导入静态库所需的HelloWorld.h头文件,并在viewDidLoad中调用[HelloWord say];
运行结果如下:


 

文/FlyingPenguin(簡書作者)
原文鏈接:http://www.jianshu.com/p/486e3b737707
著作權歸作者所有,轉載請聯繫作者獲得授權,並標註“簡書作者”。
arrow
arrow
    文章標籤
    xcode library
    全站熱搜

    龍之家族 發表在 痞客邦 留言(0) 人氣()