iOS 从C移植项目到Objective-C

一、新建项目

  iOS | Framework & Library

    Cocoa Touch Static Library

新建一个Library库

1. M.h头文件

#ifndef M_h
#define M_h

#include <stdio.h>
void testSleep(int t); void testPthread(int n); ​#endif /* M_h */

2. M.c实现文件

#include "M.h"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

void testSleep(int t)
{
   printf("testSleep:\n");
   int i;
   for (i=0; i<10; i++)
   {
       printf("sleep...\n");
       usleep(t*1000);
       printf("return...\n");
   }
}

void *thrFun(void *p)
{
   int t = (int)p;
   int i;
   for (i = 0; i<5; i++)
   {
       printf("thrFun  %d\n", t);
       sleep(1);
   }
   return NULL;
}

void testPthread(int n)
{
   void *retval;
   pthread_t *tid = (pthread_t *)malloc(sizeof(pthread_t)*n);
   int i;
   for (i=0; i<n; i++)
       pthread_create(&tid[i], NULL, thrFun, (void *)i);
   for (i=0; i<n; i++)
       pthread_join(tid[i], &retval);
}

cmd + B 编译,此时只编译模拟器了版本,可以连接手机编译真机版本静态库文件,编译成功后会在电脑上生成相关的.a静态库文件;

libM.a文件所在目录

/Users/xx/Library/Developer/Xcode/DerivedData/M-xxx/Build/Products/Debug-iphonesimulator
/Users/xx/Library/Developer/Xcode/DerivedData/M-xxx/Build/Products/Debug-iphoneos

两个路径分别是模拟器,真机版本的输出目录。

将libM.a库文件和M.h头文件拷贝到外部项目即可使用静态库里面的函数了。

二、查看 .a 文件支持的平台

通过lipo命令来查看

lipo -info xxLibrary.a

输出结果:

Architectures in the fat file: xxLibrary.a are: armv7 armv7s i386 x86_64 arm64 

上面几个平台分别对应的手机

  • armv7是iphone5之前的设备指令集架构;
  • armv7s是iphone5、iphone 5s的指令集架构;
  • arm64是iphone6、iphone 6plus的指令集架构;
  • i386以及x86_64是MAC的指令集架构;

如果某个 .a 文件只支持某一个平台,但我们的应用在发布的时候,都会需要支持所有平台的库,所以build会报错,此时可以把各个支持单个平台的 .a 文件合并。

lipo -create XXXX_V7.a XXXX_V7s.a -output XXXX_all.a

三、查看 .framework 文件支持的平台

lipo -info ./****.framework/****

输出结果:

Architectures in the fat file: ./****.framework/**** are: i386 armv7 armv7s 

如此便可查看你工程中的静态库是否支持64位。