Using Eclipse for Android C/C++ Development

Programming in C/C++ on Android is just awesome! This tutorial shows how to setup Eclipse for using C/C++ together with Java in Android projects.

0) Prerequisities

You need to have Google ADT (Android Development Tools) installed. See http://developer.android.com/sdk/eclipse-adt.html how to do it.

You also need Android ndk. Download it from http://developer.android.com/sdk/ndk/index.html and unpack it somewhere.

1) Install CDT (C/C++ Development Tools) into Eclipse.

Choose Help->Install New Software… from the main menu.

Choose http://download.eclipse.org/releases/galileo as the source site. If you have another Eclipse release than Galileo choose the appropriate url.

Click Next, Accept licences and finish the installation process.

2) In Eclipse create Android project to which you want to add C/C++ code (if you already don’t have one).

For this tutorial I’ve created simple MyAndroidProject.

3) In file manager create jni/ directory in your project directory and place your C/C++ sources file here. Also put here Android.mk file which is a makefile that tells Android build-system how to build your files.

Take a look into Android ndk docs/ANDROID-MK.html file how to create one.

Simple example of Android.mk file:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS    := -llog

LOCAL_MODULE    := native
LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)

4)  Refresh (F5) directories in Package Explorer to see jni directory here. Open your .c/.cpp file.

Your .c/.cpp file (native.c in my case) contains a lot of syntax errors which are not truly syntax errors. This is because Eclipse threats the project as a pure Java project. We have to convert the project into mixed Java & C/C++ project.

5) Press Ctrl+n (or choose File->New->Other… from main menu) and select Convert to a C/C++ Project.

This will convert your project into a mixed Java & C/C++ project rather than into pure C/C++ project (the name of the function is misleading).

Click Next. Then choose your project and below choose Makefile project and – Other Toolchain –. Click Finish.

After doing this Eclipse will ask you if you want to switch to C/C++ perspective. Choose Yes because otherwise you wouldn’t be able to set C/C++ build preferences.

6) Click on your project with right button and select Properties or press Alt+Enter

Properties windows will appear. Here you have to configure use of ndk-build instead of make all command and set proper include paths.

7) Choose C/C++ Build and configure ndk-build as a build command

In Builder settings fill ndk-build into Build command entry. You have to uncheck Use default build command. You also need to have ndk-build script in your PATH.

In Behaviour setting uncheck clean (ndk-build cleans project automatically on build and does not support separate clean command) and clear all text from build (ndk-build does not accept all as a parameter.

Click Apply to save settings.

8) Choose C/C++ General->Paths and Symbols and configure include path

In Includes tab choose GNU C or GNU C++ and click Add… button. Add path to include directory which is located in platforms/android-4/arch/arm/usr/include subdirectory of place where you’ve unpacked Android ndk. Include path depends on target for which you are compiling (android-4 in my case — i.e. Android 1.6).

Finally click Apply and OK and that is all. Now you can use all Eclipse power for editing your C/C++ sources. If you click Run or Debug Eclipse will compile C/C++ code as well as Java code and run it on device/emulator. However you will not be able to debug C/C++ code.

About these ads
This entry was posted in Android and tagged , , , . Bookmark the permalink.

68 Responses to Using Eclipse for Android C/C++ Development

  1. Bob H says:

    This looks like it runs from the projects Java interface. In NDK r5 they also have a way to just call the ‘C’ functions directly without the Java file. It use settings from the Manifest file. Have you done anything with the ‘C’ only paradigm ?

  2. MartinH says:

    Bob H: No. Actually not.

  3. tontoculo says:

    It works perfectly when modifying for C/C++ code, but when java code is modified it does not automatically rebuild it. Java modifications are not sended to emulator or device (unless you clean the project). Did you miss (or me) something?

  4. MartinH says:

    For me it works. When I modify just the Java part it rebuilds it and send to emulator without problems.

    I have sometimes problems with project not being rebuild & uploaded to device but without direct reference to if the project is mixed Java & C/C++ project or pure Java project.

    I tried to reproduce “project not being rebuild & uploaded” now, but I cannot reproduce it. It simply works as it should.

    I am using Eclipse Galileo as it is shipped with Ubuntu 10.10

  5. Ash Cairo says:

    I’m getting a (Cannot run program “ndk-build”: Unknown reason)

    error when building.

    Can anybody shed some light on this error?

    • David.Wan says:

      You sure have your ndk-build script under your PATH, or if you are under linux-based enviroment, have you granted exec priveledge for it?

    • I was having the same problem. I had defined NDKROOT=path/to/my/ndk-build and it worked from the commandline > $NDKROOT/ndk-build
      (I defined $NDKROOT in my .bashrc – ubuntu 12.04)
      And I added it to my path and made it excecutable (sudo chmod *x) Neither worked. Finally I tried Poperties->C++ Build -> “Change ${NDKROOT}/ndk-build to /home/kesten/android-ndk-r8/ and that worked. Don’t know why NDKROOT isn’t being picked up properly unless sudo chmod doesn’t affect the status when i’m user kesten.

  6. David.Wan says:

    Cool, man, it works great for me, in this way, I can write my C code mixed with the java code, and I can also debug the java code right there. The only thing that is so bad is no support for JNI debug, which makes the C/C++ debug process so hard. Do you have any clue or solution for this?

  7. David.Wan says:

    Sorry, I didn’t see your arcticle http://mhandroid.wordpress.com/2011/01/23/using-eclipse-for-android-cc-debugging/. I tried your method, but I didn’t make it. I inserted a breakpoint in my java code, and then I started the android debug seesion, after that, I ran ndk-gdb-eclipse command, and started the c&cpp debug session, then it stucked right there. The c&cpp debug session just hang right there, any clue for that?

  8. MartinH says:

    Did you place your Java breakpoint after System.load() call? If not your C/C++ code is not yet loaded into memory (and thus you cannot debug it).

    I don’t see any other obvious cause so if this doesn’t help you’re on your own.

  9. maya says:

    I read the article, and build the project succsesfuly, but I didn’t understand how do i call the c function from the java file, in your case, where and how do you call “dosomthing” function?

    thanks,
    maya

  10. Mike says:

    Thanks Martin. I was using a Java project with a Builder I created for ndk. Having the C++ project type integration into Eclipse provides a much richer IDE experience.

  11. Tobias Manthey says:

    Windows users using cygwin should replace Step 7 with the following

    In Builder settings fill
    bash -c “ndk-build”
    into Build command entry. You have to uncheck Use default build command. You also need to have the directory of ndk-build script and your cygwin\bin directory in your PATH.

    e.g PATH=C:\Android\android-ndk-r6;C:\Android\cygwin\bin;…..

    Maybe you can put this information above.

    • Kushal Vora says:

      Tobias,
      Thanks for sharing it for the Cygwin users.
      Even after doing what u said I still get error(I have included the path form ndk-build and cygwin\bin in eclipse and environment variable also):
      Program “bash” is not found in PATH
      Can please give some insights on this.

  12. Mike says:

    @Tobias – I think virtual development machines are the way to go. Why not use an Ubuntu virtual machine under VirtualBox? My VirtualBox is idling at 2% CPU and 100MB of RAM for GNOME2 under Ubuntu with Eclipse and Chrome running. Really pretty nice environment in my opinion and your get better NDK support this way and portability when you get a new host machine.

  13. Sraddhav says:

    This seems like a step by step guide to what I want to achieve : ie break into the Native code of Android.I want to run a application and while single stepping through it I want my code flow to break into the native code . Let me try this, while if you read this post plz ascertain if this is possible and if there `s anything extra I need to do to make it happen.
    Regards
    Sraddha

  14. Sraddhav says:

    Tried this it didnt work . Any idea why ?

  15. Nadav says:

    Can this work under windows using ndk-r7 and ndk-build.cmd ?

    • Nadav says:

      D:\Android\NVPACK\cygwin\bin\bash.exe -c /cygdrive/d/Android/android-ndk-r7/ndk-build should B set as the build cmd line ( also mentioned above in one of the posts )

      • mukesh says:

        where we need to write the above command”D:\Android\NVPACK\cygwin\bin\bash.exe -c /cygdrive/d/Android/android-ndk-r7/ndk-build should B set as the build cmd line”

  16. Ivo says:

    Thanks for the wonderful tutorial!
    Writing apps for Android with JNI is a lot more fun now ;).

  17. Chris says:

    Hi!

    just tried it on Linux but does not work:
    “Program “ndk-build” is not found in PATH HelloJni C/C++ Problem”
    When I open a terminal, go to the project and type “ndk-build” everything compiles fine.
    Path definitely points to “/opt/android-ndk-r6b”

    Any ideas?

  18. RetryAgain says:

    for Cygwin bash -c “ndk-build” did not work but bash -c ndk-build did
    Also the following code invoke doSomething

    public class MyAndroidProjectActivity extends Activity {
    /** Called when the activity is first created. */
    public native int doSomething();

    @Override
    public void onCreate(Bundle savedInstanceState) {
    int result = doSomething();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }

    static {
    System.loadLibrary(“native”);
    }
    }

    debugging shows result
    logcat display __android_log_print output after I added

    LOCAL_LDLIBS := -llog
    to Android.mk

    By the way monitor logcat
    I get a number of
    D/dalvikvm(214): +++ not scanning ‘/system/lib/libwebcore.so’ for ‘doSomething’ (wrong CL)
    I have not been able to find why it still works
    Good luck

  19. anuka says:

    @chris and @sodre : I’m stuck at the (Cannot run program “ndk-build” : Unknown reason) error as well. ndk-build works fine from the Terminal though, so reckon my PATH variable is fine. Tried adding my regular PATH contents [from my .bashrc] in the Eclipse -> Window -> Preferences -> C/C++ -> Build -> Environment and still no avail.
    I’m using Android ndk r7 with Helios version of Eclipse.

    Any suggestions would be appreciated.

  20. Pingback: Building native code in Eclipse « justcodingforandroid

  21. Sundar says:

    I’m using MinGw for C++ debugging on eclipse helios in windows. After studying ur blog i’ve successfully created the mixed java & C++ project. When build it days,
    “Cannot run program “ndk-build”: Launching failed)”

    I’m new to this environment… Any suggestion would be helpful

    • Niels says:

      I hope you already had some help on this issue, but in case others, as I also did, run in to this one I’ll leave my comment:
      As someone else commented setting the build command to “ndk-build.cmd” helps. I’m still having some problems because the builder is sensitive to spaces in the path, so I have to figure out a solution to my “Documents and settings” folder without screwing everything else up. Crossing my fingers that this will be my last problem in this area!

  22. Jan says:

    Did you tried the same procedure on hello-neon NDK project? I had successfully convert your example, but I cannot establish neon project. Problem is , because Eclipse does not find typedefs which are in arm-neon.h.

    E.g. int32x4_t sum_vec = vdupq_n_s32(0);
    Error: Type ‘int32x4_t’ could not be resolved

    Any suggestions would be appreciated.

    • famma says:

      I used to get many “errors” related to unresolved…
      but when I close the project and open it again and then run it inmediately it works good! But didn’t figure it out how to fix it, the problem persist after open the .c file in jni :(

  23. Karol Chudy says:

    Thank you for the fantastic tutorial with pictures. Still works today!

  24. abhishek says:

    this is working fine.but i am not able to compile c++ class. and it is giving Unsatisfiedlinkerror.

  25. nice post…
    its working fine…
    thanks for giving informative post for android cc development…
    i can easily learn form showing the snapshot….

  26. yotam says:

    for windows users, use “ndk-build.cmd” at the Build command entry.

  27. dan says:

    Very nice tutorial. I’m having trouble linking to library files with this though. I keep adding library files and library paths throught project properties but none seem to work… Any advice on this would be great. For the rest of this post I’ll go into my specific problem

    ———
    In my case I am using Irrlicht. When I open a strictly c++ project in eclipse I can build a project using the Irrlicht libraries fine… However when I follow your method I can’t seem to get it to work. To be more specific, I get this error:

    `Compile++ thumb : helloworld1 <= helloworld1.cpp
    jni/helloworld1.cpp:2:22: fatal error: irrlicht.h: No such file or directory
    compilation terminated.
    make: *** [obj/local/armeabi/objs/helloworld1/helloworld1.o] Error 1`

    I can actually get around that error by manually putting all the irrlicht.h files in the jni folder, but then I get an error about Irrlicht functions not existing so that's why I think it's a include/linker problem. I don't expect you to solve all my problems but if you could give any advice I'd appreciate it.
    ———

    • manikandan says:

      pls tell the solution for above comment i am also face the same problem while i convert c++ in android… can any provide video tutorial for it…..

  28. saul howells says:

    Martin can you please contact me i have a c++ project i need converted for android and wondered if you could help ?
    Any advice would be welcome, the code in c++ is complete and works well from qt but i need it work on android. Thanks in advance

  29. Pingback: Compiling sample JNI code in eclipse | Recent Questions | Hunt Answer

  30. jhansi says:

    I have done all the steps which you have mentioned,
    After running ndk-gdb-eclipse i tried debugging the cpp application, but i am facing an error saying “Error creating session”.
    Any help is greatly appreciated.
    Thank you.

  31. I am an android developer with java… Here i come to know that how to install and run android using C Language… this post is really nice one for me to develop android projects using c.. thanks a lot..

  32. raslanove says:

    I believe ndk-build builds incrementally and doesn’t automatically clean. That’s why there is “ndk-build clean” command.

  33. ayalcinkaya says:

    using ndk-build.cmd instead of ndk-build works for me…

  34. robi says:

    Nice one! Thank you very much for this guide!

  35. Anony says:

    Hi,

    I have tried the java jni hello project and that works just find. (it does however keep nagging me every now and then complaining
    “Description Resource Path Location Type
    Method ‘NewStringUTF’ could not be resolved hello-jni.c /HelloJni/jni line 30 Semantic Error

    It works now and then. However, I am not debugging that.

    Instead, can you help me avoid totally java/jni part. I want to write a completely native (not shared library). This piece of code compiles well using ‘mm’ (i.e the Android.mk is all fine) and works fine. I need to however debug a feature and and i am not sure how to remove the java/jni part and debug it using Eclipse. My development machine is Win7 while our build server is Ubuntu-64 to which I don’t have direct access.

  36. Pingback: Debugging native libraries for Android OS | BlogoSfera

  37. Pingback: Android NDK | codefail

  38. website says:

    Pretty nice post. I just stumbled upon your weblog and
    wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your rss feed and I hope you write again soon!

  39. Have you ever thought about writing an ebook or guest authoring on
    other sites? I have a blog centered on the same subjects you discuss and
    would love to have you share some stories/information. I know my visitors would enjoy your work.
    If you are even remotely interested, feel free to send
    me an email.

  40. Howdy.
    Someone in my Facebook group shared this site with us so I came to look it over.
    I’m enjoying the information! Fantastic blog

  41. Lee Wright says:

    I visited this blog it is nice and very informative for apps developers. Thanks for sharing this information

  42. Texstar Oil says:

    Wonderful, what a weblog it is! This blog provides helpful data to us, keep it
    up.

  43. Simply pick affiliate products to promote,
    go to relevant forums, put a link to your affiliate product in your signature, and make sales whenever somebody buys
    from your link. When you market to the masses, you seldom hit the mark with any individual.
    If you can answer these questions in the form of a video, this is an even better way to communicate to them.

  44. I am really pleased to glance at this website posts which includes plenty of useful information, thanks
    for providing these kinds of statistics.

  45. Halra says:

    still try to using eclipse,
    need more tutorial for this because i’m a newbie,
    thank you very much

  46. I used to be recommended this web site via my cousin. I am not certain whether this put up is written by
    him as no one else understand such certain about my problem.
    You are incredible! Thanks!

  47. It’s a shame you don’t have a donate button! I’d certainly donate to
    this brilliant blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this site with
    my Facebook group. Chat soon!

  48. Pingback: Eclipse에 Android Open Source Project(AOSP) 세팅하기 – rapaellk's blog

  49. Memory says:

    I was suggested this web site by means of my cousin. I am now not
    sure whether or not this put up is written by way of him as no one else know such specified about my problem.
    You’re amazing! Thanks!

  50. When I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and now every
    time a comment is added I recieve four emails with the exact same comment.
    Perhaps there is a means you can remove me from that service?
    Many thanks!

  51. botosis says:

    Here are the potential skin care benefits of the ingredient.
    If it contains petrolatum or mineral oil, it will cause excessive greasiness and could clog your pores,
    leading to blemishes. Probably one of the most important components of skin health is Vitamin A.

  52. Cerys says:

    Hey There. I discovered your blog using msn. This is a really smartly written article.
    I will make sure to bookmark it and come back to read more of your helpful info.
    Thank you for the post. I will definitely comeback.

  53. title says:

    Hello there, I think your website could possibly be having web browser compatibility
    problems. When I look at your site in Safari, it looks fine
    however, if opening in Internet Explorer, it’s got some overlapping issues.
    I merely wanted to provide you with a quick heads up! Aside from that, excellent blog!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s