Android NDK startup

This is a simple tutorial or you can say a collection of code for Android NDK beginners. It is possible to compile android native code using android NDK aka Native Development Kit or Android Source. Using android source is better because we can use more features that comes with android but not available in NDK. Now I will try to show both way. I prefer to use terminal/console for compiling the code and using a text editor (like sublime text) and a unix environment (linux/os x). Though one can use Eclipse as IDE for NDK. The first method here is using Eclipse IDE and NDK. One can easily  google for how to add NDK plugin in eclipse.

Method 1. Using Eclipse

Download ndk, sdk, eclipse. Add android sdk/ndk plugin to eclipse.

Create a new Android project. Right Click on the project in project explorer->Android tools->add native support. Then you will find a jni folder in your project. This folder contains a cpp file and file (make file).
Edit the cpp file as follows

extern "C" {
int Java_com_example_ndkexample_MainActivity_add(JNIEnv *env, jobject thiz, int a, int b)
	return (a+b);

JNI for android is much simpler then JNI in java. This method takes two int as input and returns their sum. Edit, add the cpp file as local_src_files and add a name for your library, this name will be used to load the library. Here is my sample

LOCAL_MODULE    := test
LOCAL_SRC_FILES := test.cpp

Right click on the project, build project. In your java MainActivity load the library statically. Add the native function.

public class MainActivity extends Activity {

	public native int add(int a, int b);
	protected void onCreate(Bundle savedInstanceState) {
		int r=add(1,2);
		Log.d("ndkexample", "The sum of 1 and 2 is "+r);

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(, menu);
		return true;



If you run the project, you will see the result in log.

2. Using command line
The initial steps are similar, create a new project in eclipse and create a jni folder there. Add source file and file.
Now add the ndk folder in your path variable. Open terminal and CD to the project/jni folder.
Run command: ndk-build. It will compile the source code, create the library file and save it to libs/armeabi folder (same what as ide, just more manual). Run the project as previous.

Android NDK startup

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s