Skip to content

Most visited

Recently visited

navigation

Add C and C++ Code to Your Project

You can add C and C++ code to your Android project by placing the code into a cpp directory in your project module. When you build your project, this code is compiled into a native library that Gradle can package with your APK. Your Java or Kotlin code can then call functions in your native library through the Java Native Interface (JNI). If you want to learn more about using the JNI framework, read JNI tips for Android.

Android Studio's default build tool for native libraries is CMake. Android Studio also supports ndk-build due to the large number of existing projects that use the build toolkit to compile their native code. If you want to import an existing ndk-build library into your Android Studio project, learn how to link Gradle to your native library project. However, if you are creating a new native library, you should use CMake.

This page shows you how to set up Android Studio with the necessary build tools, create a new project with C/C++ support, and add new C/C++ files to your project.

If instead you want to add native code to an existing project, you need to follow these steps:

  1. Create new native source files and add them to your Android Studio project.
    • You can skip this step if you already have native code or want to import a prebuilt native library.
  2. Configure CMake to build your native source code into a library. You also require this build script if you are importing and linking against prebuilt or platform libraries.
    • If you have an existing native library that already has a CMakeLists.txt build script, or uses ndk-build and includes an Android.mk build script, you can skip this step.
  3. Configure Gradle by providing a path to your CMake or ndk-build script file. Gradle uses the build script to import source code into your Android Studio project and package your native library (the SO file) into the APK.

Once you configure your project, you can access your native functions from Java or Kotlin code using the JNI framework. To build and run your app, simply click Run run then run app from the menu bar.

Note: If your existing project uses the deprecated ndkCompile tool, you should migrate to using either CMake or ndk-build. To learn more, go to the section about how to Migrate from ndkCompile.

Attention experimental Gradle users: Consider migrating to plugin version 2.2.0 or higher, and using CMake or ndk-build to build your native libraries if any of the following apply to you: Your native project already uses CMake or ndk-build; you would rather use a stable version of the Gradle build system; or you want support for add-on tools, such as CCache. Otherwise, you can continue to use the experimental version of Gradle and the Android plugin.

Download the NDK and Build Tools

To compile and debug native code for your app, you need the following components:

You can install these components using the SDK Manager:

  1. From an open project, select Tools > Android > SDK Manager from the menu bar.
  2. Click the SDK Tools tab.
  3. Check the boxes next to LLDB, CMake, and NDK, as shown in figure 1.

    Note: The SDK Manager includes forked versions of CMake up to version 3.6.4. If you want to use later versions of CMake, go to the section about using CMake 3.7 or higher.

    Figure 1. Installing LLDB, CMake, and the NDK from the SDK Manager.

  4. Click Apply, and then click OK in the pop-up dialog.
  5. When the installation is complete, click Finish, and then click OK.

Use CMake 3.7 or higher

The SDK Manager includes forked versions of CMake up to version 3.6.4. If you want to use CMake version 3.7 or higher, proceed as follows:

  1. Update Android Studio to 3.0 or higher, and update the Android plugin for Gradle to 3.0.0 or higher.

    Warning: Android plugin 3.0.0 and higher introduce some breaking changes that you should first consider. To learn more, read Migrate to Android Plugin for Gradle 3.0.0.

  2. Download and install CMake 3.7 or higher from the official CMake website.
  3. Include the path to the CMake installation in your project's local.properties file:
    cmake.dir="path-to-cmake"
  4. Alternatively, you can add the path to the CMake installation to your PATH environment variable and specify the CMake version in your module's build.gradle file:
    android {
        ...
        externalNativeBuild {
            cmake {
                ...
                // When you specify a version of CMake, as shown below,
                // the Android plugin searches for its binary within your
                // PATH environmental variable.
                version "3.7.1"
            }
        }
    }
    

Warning: Support for using CMake 3.7 and higher with Android Studio is a preview feature. If you experience any issues, please report a bug.

Create a New Project with C/C++ Support

Creating a new project with support for native code is similar to creating any other Android Studio project, but there are a few additional steps:

  1. In the Configure your new project section of the wizard, check the Include C++ Support checkbox.
  2. Click Next.
  3. Complete all other fields and the next few sections of the wizard as normal.
  4. In the Customize C++ Support section of the wizard, you can customize your project with the following options:
    • C++ Standard: use the drop-down list to select which standardization of C++ you want to use. Selecting Toolchain Default uses the default CMake setting.
    • Exceptions Support: check this box if you want to enable support for C++ exception handling. If enabled, Android Studio adds the -fexceptions flag to cppFlags in your module-level build.gradle file, which Gradle passes to CMake.
    • Runtime Type Information Support: check this box if you want support for RTTI. If enabled, Android Studio adds the -frtti flag to cppFlags in your module-level build.gradle file, which Gradle passes to CMake.
  5. Click Finish.

After Android Studio finishes creating your new project, open the Project pane from the left side of the IDE and select the Android view. As shown in figure 2, Android Studio adds the cpp and External Build Files groups:

    Figure 2. Android view groups for your native sources and external build scripts.

    Note: This view does not reflect the actual file hierarchy on disk, but groups similar files to simplify navigating your project.

  1. The cpp group is where you can find all the native source files, headers, and prebuilt libraries that are a part of your project. For new projects, Android Studio creates a sample C++ source file, native-lib.cpp, and places it in the src/main/cpp/ directory of your app module. This sample code provides a simple C++ function, stringFromJNI(), that returns the string "Hello from C++". You can learn how to add additional source files to your project in the section about how to Create new native source files.

    Known Issue: Android Studio currently shows you only the header files that have matching source files—even if you specify other headers in your CMake build script. See Issue #38068472

  2. The External Build Files group is where you can find build scripts for CMake or ndk-build. Similar to how build.gradle files tell Gradle how to build your app, CMake and ndk-build require a build script to know how to build your native library. For new projects, Android Studio creates a CMake build script, CMakeLists.txt, and places it in your module’s root directory. To learn more about the contents of this build script, read Configure CMake.

Build and run the sample app

When you click Run run then run app from the menu bar, Android Studio builds and launches an app that displays the text "Hello from C++" on your Android device or emulator. The following overview describes the events that occur in order to build and run the sample app:

  1. Gradle calls upon your external build script, CMakeLists.txt.
  2. CMake follows commands in the build script to compile a C++ source file, native-lib.cpp, into a shared object library and names it libnative-lib.so, which Gradle then packages into the APK.
  3. During runtime, the app's MainActivity loads the native library using System.loadLibrary(). The library’s native function, stringFromJNI(), is now availableto the app.
  4. MainActivity.onCreate() calls stringFromJNI(), which returns "Hello from C++", and uses it to update the TextView.

Note: Instant Run is not compatible with components of your project written in native code.

If you want to verify that Gradle packages the native library in the APK, you can use the APK Analyzer:

  1. Select Build > Analyze APK.
  2. Select the APK from the app/build/outputs/apk/ directory and click OK.
  3. As shown in figure 3, you can see libnative-lib.so in the APK Analyzer window under lib/<ABI>/.

    Figure 3. Locating a native library using the APK Analyzer.

Tip: If you want to experiment with other Android apps that use native code, click File > New > Import Sample and select a sample project from the Ndk list.

Create New C/C++ Source Files

To add new C/C++ source files to an existing project, proceed as follows:

  1. If you don't already have a cpp/ directory in the main source set of your app, create one as follows:
    1. Open the Project pane from the left side of the IDE and select the Project view from the drop-down menu.
    2. Navigate to your-module > src, right-click on the main directory, and select New > Directory.
    3. Enter cpp as the directory name and click OK.

  2. Right-click on the cpp/ directory and select New > C/C++ Source File.
  3. Enter a name for your source file, such as native-lib.
  4. From the Type drop-down menu, select the file extension for your source file, such as .cpp.
    • You can add other file types to the drop-down menu, such as .cxx or .hxx, by clicking Edit File Types . In the C/C++ dialog box that pops up, select another file extension from the Source Extension and Header Extension drop-down menus and click OK.
  5. If you also want to create a header file, check the Create an associated header checkbox.
  6. Click OK.

After you add new C/C++ files to you project, you still need to configure CMake to include them in your native library.

Migrate from ndkCompile

If you're using the deprecated ndkCompile, you should migrate to using either CMake or ndk-build. Because ndkCompile generates an intermediate Android.mk file for you, migrating to ndk-build may be a simpler choice.

To migrate from ndkCompile to ndk-build, proceed as follows:

  1. Compile your project with ndkCompile at least once by selecting Build > Make Project. This generates the Android.mk file for you.
  2. Locate the auto-generated Android.mk file by navigating to project-root/module-root/build/intermediates/ndk/debug/Android.mk.
  3. Relocate the Android.mk file to some other directory, such as the same directory as your module-level build.gradle file. This makes sure that Gradle doesn't delete the script file when running the clean task.
  4. Open the Android.mk file and edit any paths in the script such that they are relative to the current location of the script file.
  5. Link Gradle to the Android.mk file .
  6. Disable ndkCompile by opening the build.properties file and removing the following line:
    // Remove this line
    android.useDeprecatedNdk = true
    
  7. Apply your changes by clicking Sync Project in the toolbar.
This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Follow Google Developers on WeChat

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)