Sunday, October 23, 2016

How to Mark C/C++ Files in Android Studio

UPDATED: please refer to this post for much simpler way! The instruction below is officially deprecated.

There are basically two ways to link native C/C++ files in Android Studio. One way is to use CMake, and the other is to use NDK-BUILD tool. In OpenCV Android samples, it does it by NDK-BUILD tool. as you can see here. However, the problem with NDK-BUILD method is that Android Studio does not treat JNI native source files as C/C++ files; it is quite annoying to code directly in Android Studio when you don't have function-completion features or auto-syntax checks, etc.

Here, I will show you how to trick Android Studio to mark JNI native source files as C/C++ files when building with NDK-BUILD method. Basically, I will add CMake file to link C/C++ file folder for compilation so that Android Studio will mark all C/C++ files in the folder as C/C++ with correct syntax guide. For more info on adding C/C++ support in Android Studio, refer to Google's official documentation.

First, Install NDK and CMake components for your Android Studio. Also make sure that you are running Android Studio 2.2 or higher.

Locate C/C++ files that are linked with your Android project. This is probably src/main/jni folder in the app module directory. Create an empty C/C++ file in the folder: src/main/jni/empty.cpp.

Next, create CMakeLists.txt file in the app's directory with the following content:
cmake_minimum_required(VERSION 3.4.1)
             src/main/jni/empty.cpp )

The last parameter should point to the newly created empty C/C++ file. Also make sure to add as many include directories as needed. 

Next, add the following lines in the app module's build.gradle file:
android {
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"

Now, sync gradle file and compile. You will notice that Android Studio now considers all C/C++ files in the src/main/jni folder as native C/C++ files. You can now directly edit your C/C++ files from Android Studio with syntax checks, method completion, etc!

No comments:

Post a Comment