iOS架构-c++工程在Mac下编译成.a库并调用(12)

请先了解:xcode生成静态库文件.a

前言: 有时侯需要使用c++的一些代码库,这里先讲一下用Xcode 建C++ 工程,并将代码编译成.a库,提供给demo使用。这里只是简单的介绍,以后会继续介绍如何将公开的C/C++源码编译成OC使用的静态库.a。

第一步 准备

a. Xcode 新建一个 c++ 工程 CPPtest(macoOS 平台下)
在这里插入图片描述选择C++
在这里插入图片描述

b. 新建一个类 world
在这里插入图片描述

world.hpp 代码

//
//  Created by lzz on 2019/5/5.

#ifndef world_hpp
#define world_hpp

#include <stdio.h>

class TestA
{
    public: TestA(){};
    virtual ~TestA(){};
    virtual void test(const char *str);
    virtual void helloWorld();
};

#endif /* world_hpp */

world.cpp 代码

//
//  Created by lzz on 2019/5/5.

#include "world.hpp"

void TestA::helloWorld()
{
    printf("==== helloWorld,I'm test lib ==== \n");
}

void TestA::test(const char *str)
{
    printf("==== say:%s in lib ==== \n",str);
}

c. main.cpp 中调用

//
//  Created by lzz on 2019/5/5.

#include <iostream>
#include "world.hpp"

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
 
    // 方式一:箭头
    TestA *aaa = new TestA();
    aaa->helloWorld();
    aaa->test("aaa");
    
    // 方式二;打点
    TestA bbb = TestA();
    bbb.helloWorld();
    bbb.test("bbb");
    
    return 0;
}

run 通过即可。

第二步:编译

终端:cd 文件所在的目录
在这里插入图片描述
** a, 编译成.o 指定x86_64架构 **

clang++ -arch x86_64 -g -o world.o world.cpp -c

** b, 打包成.a库 **

ar -r libworld.a world.o

在这里插入图片描述
** c, 查看.a库支持架构 **

lipo -info libworld.a

结果:Non-fat file: libworld.a is architecture: x86_64

第三步:导入demo 使用
  1. #warning 把引用c++库的 .m 改成.mm 即可编译,否则总是报错 不支持_86_64

  2. 将.a 和 world.hpp 导入demo工程中,使用和在main.cpp 使用一样。
    在这里插入图片描述

  3. 运行成功输出。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值