我知道如何使用 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/