簡體   English   中英

如何為ios應用程序構建和使用C ++靜態庫

[英]How to build and use a C++ static library for ios application

我知道如何在xcode 4.6中使用iOS->Framework&Library->Cocoa Touch Static Library構建一個對象C靜態庫,借助本教程在iOS教程中創建靜態庫,它非常簡單。 但是,我不確定的一件事是如何為io應用程序構建和使用純C ++靜態庫。 為了構建C ++靜態庫,我也使用iOS->Framework&Library->Cocoa Touch Static Library指南,不同之處在於我在創建靜態庫項目時刪除所有.h和.m文件然后放入所有C ++項目中的靜態庫頭文件和實現文件。 一個非常簡單的例子如下:

hello.h

#include <iostream>
void say_hello();

HELLO.CPP

#include "hello.h"

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

它似乎工作,我可以為iPhone 6.1模擬器構建hello.a靜態庫。 下一步是構建一個將調用靜態庫的應用程序。 我為iPhone 6.1模擬器構建了一個簡單的iOS application->Single View Application ,然后嘗試在ViewController.mm文件中調用hello.a靜態庫(將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): 

錯誤1:

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 ++靜態庫的方式有問題嗎?

  • 在我的例子中,當調用靜態庫時,我該如何解決鏈接錯誤?

非常感謝。

這樣做,

1)在Xcode 6中使用相同的方式創建c ++庫,iOS-> Framework&Library-> 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)然后在文件瀏覽器視圖中展開產品。 選擇你的.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觸摸類文件,它將充當靜態庫和obejective -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)現在在任何目標c文件中使用此MyCustomAdaptor。

請注意你的.a是用i386或armv7構建的嗎? 通常,您應該構建兩個版本並將它們合並為一個版本。 像這樣:lipo -create -output libopencore-amrwb.a libopencore-amrwb-armv7.a libopencore-amrwb-i386.a

我現在和你一樣。 我在這里描述了同樣的問題,實際上是同樣的兩個錯誤。

在構建庫時,您必須記住要在哪里使用它,iOS設備或模擬器。 這很重要,因為你必須為不同的情況構建,這很簡單,當你構建你的庫時,只需檢查“選擇方案”。

對於Real設備使用:

在此輸入圖像描述

只是為了在模擬器中測試使用:

在此輸入圖像描述

構建之后,只需將創建的文件拖放到您想要使用庫的項目中,就可以了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM