ndk學習5: ndk中使用c++



默認情況下ndk不支持標准C++庫,異常, rtti等

 

在ndk文檔有關於C++ support的詳細介紹

 

一. 使用C++標准庫

介紹:

默認是使用最小額度的C++運行時庫, 在Application.mk中添加APP_STL指明所需要的庫

需要注意的是,目標手機或者模擬器上可能沒有下面的共享庫,此時就需要你作為靜態庫使用

ndk中各種庫的支持情況

 

PS: stlport和gnustl的區別

    Android NDK不提供STL的原因應該是因為版權問題。因為標准的GNU STL是由libstdc++提供的,本身雖然是GPL,但是只要不修改它的代碼,就可以自由使用。而在Android平台上,因為很多適配上的問題,不經修改的libstdc++是無法直接使用的,所以NDK無法直接提供。STLport沒有此類限制,所以是比較好的替代解決方案

 

 

使用stlport:

以使用stlport為例子:

 

1.Application.mk中加入

APP_STL := stlport_static 

    PS: 有的手機或者模擬器中可能沒有stlport_shared,運行時可能會報錯

 

編寫代碼

#include <iostream>

#include <stdio.h>

using namespace std;

int main(int argc, char* argv[]) {

    cout << "Hello World" << endl;

    return 0;

} 

 

編譯完后:

 

stlport需要包含stlport的庫進來在

android-ndk-r10b\sources\cxx-stl目錄下有對應版本的stl

比如我們要使用stlport 其頭文件一般在

E:\Android\android-ndk-r10b\sources\cxx-stl\stlport\stlport

把上面的路徑添加到paths and symbols即可

   

成功運行:

 

此時可以使用stl中的各種數據結構,比如map

#include <map>

#include <iostream>

#include <string>

using namespace std;

int main(int argc, char* argv[]) {

    map<int,string> mapStudent;

    mapStudent.insert(map<intstring>::value_type(1,"bing1"));

    mapStudent.insert(map<intstring>::value_type(2,"bing2"));

    mapStudent.insert(map<intstring>::value_type(3,"bing3"));

    mapStudent.insert(map<intstring>::value_type(4,"bing4"));

    map<intstring>::iterator iter;

    for (iter = mapStudent.begin();iter != mapStudent.end();iter++) {

        cout << (*iter).first << " " << (*iter).second << endl;

    }

    return 0;

} 

 

運行結果如下:

 

 

.使用異常

 

需要注意的幾點:

1. NDK 5之后才支持C++異常

2. 可以在在android.mkApplication.mk中添加使用異常,

    區別是android.mk是局部的

    Application.mk是全局的

 

添加完畢即可使用

#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {

    try {

        cout << "Hello World" << endl;

    } catch (...) {

        cout << "error" << endl;

    }

    return 0;

} 

 

運行:

 

 

 

.使用RTTI

同異常一樣,不多做介紹

 

代碼:

#include <iostream>

#include <typeinfo>

using namespace std;

class CNumber

{

};

int main(int argc, char* argv[])

{

    CNumber nNum ;

    cout << typeid(nNum).name() << endl;

    cout << "Hello World" << endl;

} 

 

運行:

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM