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-r10bsourcescxx-stl目录下有对应版本的stl

比如我们要使用stlport 其头文件一般在

E:Androidandroid-ndk-r10bsourcescxx-stlstlportstlport

把上面的路径添加到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;

} 

 

运行:

 

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/bingghost/p/5723982.html