AS中ndk-build方式cpp问题集锦

想用c++代码在Java中调用,以前也一直OK调用.so库和jni接口,但不知道为何在AS3.0上一直报标准库找不到;html

还有一个变更就是AS2.2之后ndk编译默认采用cmake了,这就致使之前的Android.mk和Application.mk文件写法不行了;但为了方便仍是使用了ndk-build方式(这块官方文档也是用的cmake,都没有ndk-build教程了,哎~)。没办法,以前对这块没经验,因此开始了填坑之旅。java

目前还只有一个问题,之后填了新坑再补充。android

问题:找不到相似string和std等标准库函数

首先要使用ndk-build形式进行编译cpp代码,须要修改一下build.gradle文件,如今新建c++项目都是用cmake了,因此咱们若是不用cmake要用mdk-build的话,须要改build.gradle文件;直接贴代码:c++

改动一:build.gradle

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.zhc.jnidemo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            ndkBuild {
                // Sets optional flags for the C compiler.
                cFlags "-D_EXAMPLE_C_FLAG1", "-D_EXAMPLE_C_FLAG2"

                // Sets a flag to enable format macro constants for the C++ compiler.
                cppFlags "-D__STDC_FORMAT_MACROS"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path "src/main/jni/Android.mk"
        }
    }
}

改动二:Android.mk、Application.mk

这两个makefile文件都是在jni目录下的
image.pngapp

Android.mk以下:ide

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE := native
LOCAL_SRC_FILES := native-lib.cpp
LOCAL_LDLIBS    := -llog
include $(BUILD_SHARED_LIBRARY)

Application.mk以下函数

#APP_OPTIM := release
APP_PLATFORM := android-15
APP_ABI := armeabi-v7a
NDK_TOOLCHAIN_VERSION=4.9
APP_PIE := false
# 重点是这句话:
APP_STL := stlport_static
APP_CFLAGS := -O3 -Wall -pipe \
    -ffast-math \
    -fstrict-aliasing -Werror=strict-aliasing \
    -Wno-psabi -Wa,--noexecstack \
    -DANDROID -DNDEBUG

如今再clean项目,从新编译项目,就发现相似#include <string>找不到的问题没有了,但愿你们也能解决相同问题。gradle

问题:找不到C++ 11标准库shared_ptr

Android.mk文件中添加APP_CFLAGS := -std=c++11便可支持c++ 11函数,而后在APP_STL := 中指定gnustl_static能够支持最多的函数库。能够查看官方文档:C++ 库支持ui

#APP_OPTIM := release
APP_PLATFORM := android-15
APP_ABI := armeabi-v7a
NDK_TOOLCHAIN_VERSION=4.9
APP_PIE := false
APP_STL := gnustl_static
APP_CFLAGS := -O3 -Wall -pipe \
    -ffast-math \
    -fstrict-aliasing -Werror=strict-aliasing \
    -Wno-psabi -Wa,--noexecstack \
    -DANDROID -DNDEBUG \
    -std=c++11

问题:must be enabled with the -std=c++11 or -std=gnu++11 compiler options

解决办法是在Android.mk文件中加入支持c++11的flagspa

LOCAL_CFLAGS += -std=c++11

问题:More than one file was found with OS independent path

Error:Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
More than one file was found with OS independent path 'lib/armeabi-v7a/libnative-lib.so'

删除build.gradle下面的:

// 删除一下代码
    sourceSets.main {
        jniLibs.srcDir('src/main/libs')
    }
相关文章
相关标签/搜索