Android Module配置C++支持
AndroidStudio提供了创建项目时选择C++支持的模板,但是新建Module的时候并没有C++模板,
要如何配置Module的C++支持呢? 虽然Module没有提供C++模板,但是我们可以手动配置C++支持.
首先新建 Android Library
然后在 src/main/
新建cpp文件夹,之后在cpp文件夹新建一个 main.cpp
的C/C++ Source File文件.
再新建一个CMakeLists.txt
文件,复制下面的内容到CMakeLists.txt
文件.
一个更简单的方法,先去建一个支持C++的项目,然后将cpp文件夹直接拷贝到src/main
目录下.
# 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.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
main #新建的C/C++ Source File文件的名称
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
#main.cpp源文件
main.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.
main
# Links the target library to the log library
# included in the NDK.
${log-lib} )
去模块的 build.gradle
中添加下面的配置
android{
defaultConfig{
...
...
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
}
android{
...
...
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
}
生成的aar可以拷贝到别的项目中使用(需要配置NDK,不然会报错)