c++ - 如何为 ios 应用程序构建和使用 C++ 静态库

标签 c++ ios objective-c xcode static-libraries

我知道如何使用 iOS->Framework&Library->Cocoa Touch Static Library 构建对象 C 静态库在 xcode 4.6 中,在本教程的帮助下很简单 Creating a Static Library in iOS Tutorial .但是,我不确定的一件事是如何为 io 应用程序构建和使用纯 C++ 静态库。为了构建 C++ 静态库,我也使用 iOS->Framework&Library->Cocoa Touch Static Library guideline,不同的是我在创建静态库项目的时候把.h和.m文件全部删除,然后把所有的C++静态库头文件和实现文件放到项目里面。一个非常简单的例子如下:

你好.h

#include <iostream>
void say_hello();

你好.cpp

#include "hello.h"

void say_hello()
{
std::cout<<"hello"<<std::endl;
}

它似乎有效,我可以构建 hello.a iPhone 6.1 模拟器的静态库。下一步是构建将调用静态库的应用程序。我构建了一个简单的 iOS application->Single View Application对于 iPhone 6.1 模拟器,然后尝试调用 hello.a ViewController.mm 中的静态库文件(将 ViewController.m 更改为 ViewController.mm 以便它可以调用 C++ 函数)只需使用以下代码:

say_hello();

但是,我收到一条警告和两条错误消息:

警告:

ld: warning: ignoring file hello.a, file was built for archive which is not the architecture being linked (i386): 

错误一:

hello.a
Undefined symbols for architecture i386:
  "say_hello()", referenced from:
      -[ViewController viewDidLoad] in ViewController.o

错误 2:

ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

然后我有几个与这个实验相关的问题:

  • 创建纯 C++ 静态库的方法是否正确?
  • 我调用 C++ static 的方式有问题吗 图书馆?

  • 在我的例子中,调用静态库时,如何解决链接错误?

非常感谢。

最佳答案

这样就可以了,

1)使用相同的方式创建 c++ 库,iOS->Framework&Library->Xcode 6 中的 Cocoa Touch Static Library。

TestCPlusPlus.h

int sub(int a, int b);

TestCPlusPlus.cpp

int sub(int a, int b)
{
 return a - b;
}

2) 构建保持配置iOS设备的静态库,然后是iPhone 6(基本上是模拟器。)

3) 然后在文件浏览器 View 中展开产品。选择您的 .a 文件,例如 libTestStaticLibrary.a ,然后选择右键 > 在 Finder 中显示。在文件夹中向上移动。您应该能够看到两个 folers Debug-iphoneos 和 Debug-iphonesimulator

4) 现在 打开终端转到此产品路径,然后键入

lipo -create Debug-iphoneos/libTestStaticLibrary.a Debug-iphonesimulator/libTestStaticLibrary.a -output libTestStaticLibrary.a

5) 现在打开你使用这个库的项目,你需要拖放静态库文件以及静态库函数的函数声明的头文件。

6) 现在,创建 Cocoa touch 类文件,它将充当静态库和目标 -c 文件之间的适配器。将扩展名更改为 .mm

MyCustomAdaptor.h

@interface MyCustomAdaptor : NSObject

-(int)getSub:(int ) a SecondParam:(int) b;

@end

MyCustomAdaptor.mm

#import "TestCPlusPlus.h"

@implementation MyCustomAdaptor

-(int)getSub:(int ) a SecondParam:(int) b
{
 int c = sub(a,b);
 return c;
}

@结束

7) 现在在任何 objective-c 文件中使用此 MyCustomAdaptor。

关于c++ - 如何为 ios 应用程序构建和使用 C++ 静态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811072/

相关文章:

c++ - 如果已最小化,如何恢复 winapi 窗口?

objective-c - 我在此Objective-C方法中发生内存泄漏,有人可以告诉我在哪里吗?

C++ 精度 - setprecision 的行为

c++ - 将函数指针作为参数从 C 代码传递到 C++ 库

ios - TKChartDataPoint 不符合预期的类型序列

ios - 在单个 UICollectionViewController 中管理多个 UICollectionViewLayout

ios - iOS 上使用 Memory Monitor 时虚拟内存消耗和实际内存的区别

ios - 带有 : ERROR: Cannot find schemes 的 Travis-CI

c++ - C++ 中的动态绑定(bind)示例

c++ - 使用赋值是危险的,因为之前的值无效