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

前言: 有时侯需要使用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. 运行成功输出。

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...