Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio + NDK - Import Existing C++

How can I both include in the compilation and view in the project file tree some .h and .cpp files located outside of the project directory ?

With Visual Studio and a C++ project you would simply use "Add existing item", select your files and voilà, it just works in ten seconds. Aren't Android-based development supposed to make developper's lives easier ? :/

I've been searching for hours how to do this now. None of the answers I found is addressing this.

I can't beleive that, among all the people who have been using Android Studio with the NDK, none of them have used C++ code outside of the jni folder...

Do you know how to do ? Thank you.

like image 265
Virus721 Avatar asked Sep 21 '15 13:09

Virus721


1 Answers

Here's what I've done. First install newest Android Studio 1.4 released today (but I worked on first 1.3 preview with ndk support). To have NDK support you'll need to switch to Gradle 2.5 (Project Structure -> Project -> Gradle Version). Use experimental gradle-plugin (in main build.gradle "classpath 'com.android.tools.build:gradle-experimental:0.2.0'").

Then you need to update your apps build.gradle file to new format as explained here: http://tools.android.com/tech-docs/new-build-system/gradle-experimental

My project consisted of a static lib and dynamic lib. Unfortunately this is not supported and you must compile it as one dynamic lib for now. Custom makefiles are not supported.

This is the tricky part, you need to put it inside model { }

android.ndk {
    moduleName = "NativeLib"

    // toolchain = "clang" <- tried using it, but failed
    // toolchainVersion = "3.5"

    stl = "gnustl_static" // you can switch stl lib this way

    ldLibs += "log"
    cppFlags += "-g"
    cppFlags += "-std=c++11" // use c++11
    cppFlags += "-Wall"
    cppFlags += "-I${file("../../../common/include")}".toString() // include folder
}

android.sources {
    main {
        jni {
            source {
                srcDirs = ['src/main/jni', '../../../common']
            }
        }
    }
}

You can change the paths if your native source files reside elsewhere - this is from my project structure.

like image 75
serine Avatar answered Nov 14 '22 10:11

serine