天天看点

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

1.首先引入第三方包:

打开下载好的fmod包,进入lib

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

将这些全部复制到我们项目的app/libs下:(这些so是作为预编译库用来编译我们的自己的库的,没有的话不能生成我们自己的.so)

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

然后打开fmod的inc目录下:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

全部复制到app/src/main/cpp/fmod_inc : (理论上这个目录自己建立就可以,然后在CmakeList.txt里面配置,使项目能找到)

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

这里完成一个最简单的例子,使用fmod播放声音,到fmod的examples目录下,将下面的文件复制到项目cpp文件夹下:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

最后将examples里的示例MainActivity复制到自己的项目中,我自己建立了一个包用来存放:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

然后在AndroidManifest.xml中启动项替换原来的MainActivity:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

好的,到这里,所有的引入已经完成;

2.配置编译

首先来看一下我配置的CmakeList.txt:(详细解释,已经把CmakeList.txt 各种重点解释的很详细了)

# For more information about using CMake with Android Studio, read the

# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

#这是我加入的fmod头文件的目录,为了能让cpp找到,加入到这里

include_directories(

./src/main/cpp/fmod_inc

)

#设置变量,方便下面使用 ,使用变量格式${distribution_DIR}

set(distribution_DIR ${CMAKE_SOURCE_DIR}/libs)

#添加fmod预编译库

add_library(

#预加载库的名称

fmod

#表示是动态库

SHARED

#表示这个库是引入的

IMPORTED

)

#配置加载动态库的路径

set_target_properties(

#动态库名称

fmod

PROPERTIES IMPORTED_LOCATION

#寻找的动态库.so文件路径,${ANDROID_ABI}就是表示各种平台,armeabi或x86等。注意在这个目录下必须有对应的.so文件,不然会报错链接失败

${distribution_DIR}/${ANDROID_ABI}/libfmod.so

)

#添加fmodL预编译库,同上

add_library(

fmodL

SHARED

IMPORTED

)

set_target_properties(

fmodL

PROPERTIES IMPORTED_LOCATION

${distribution_DIR}/${ANDROID_ABI}/libfmodL.so

)

#添加自己要生成的库

add_library(

play_sound

SHARED

src/main/cpp/play_sound.cpp

src/main/cpp/common_platform.cpp

src/main/cpp/common.cpp

)

#*********************************************

# Searches for a specified prebuilt library and stores the path as a

# variable. Because CMake includes system libraries in the search path by

# default, you only need to specify the name of the public NDK library

# you want to add. CMake verifies that the library exists before

# completing its build.

find_library( # Sets the name of the path variable.

log-lib

# Specifies the name of the NDK library that

# you want CMake to locate.

log )

# Specifies libraries CMake should link to your target library. You

# can link multiple libraries, such as libraries you define in this

# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries(

# Specifies the target library.

# 目标库(一个target_link_libraries标签只有一个)

play_sound

# Links the target library to the log library

# included in the NDK.

# 依赖于库(可以有多个,指上边库的生成过程依赖于下面的库)

fmod

fmodL

${log-lib} )

最后还有一个问题,打开common_platform.cpp,我们发现有几个对应的native的实现函数:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

发现他们是对应示例MainActivity里的native函数:

Android NDK系列二(cmake方式配置第三方库(fmod库为例))

我自己引入的时候包名改了,所以要把common_platform.cpp里的native实现的函数包名替换成现在的包名;

大事搞成!