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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shifang07/article/details/89916089

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

猜你喜欢

转载自blog.csdn.net/shifang07/article/details/89916089