Alex Rivera | Logout

How to compile C into an executable binary file and run it in Android from Android Shell?

Asked 2012-03-26T07:39:51.860
48

I have a Device on which I installed Android Gingerbread 2.3.4 Here i want to run C executable file on android device

I am able to run android NDK application on this Device and it runs perfect. But I want to run only one hello.c executable file on the Device.

/* #includes #defines ... */

int main(){
    // Do something when this is executed
    return 0;
}

Is there any way to compile this file with Android NDK tool chain so I can run this file's executable?

I found one thing here but this is not working for me. I am using Android NDK, Revision 7b for Linux. There is no directory structure like this.

Edit
Report

2 Answers

40

First, let me say that my answer is dependent on your using NDK r7b (it'll work for r7c as well) on Linux (change paths appropriately for other systems).

Edit: Last tested with NDK r8e on Linux and Nexus 4 with adb from SDK Platform-Tools Rev 18 on Windows 7 (latest as of 2013-07-25) without root access.

Yet Another Edit: Please read this question for altering my instruction for native binaries that need to run on Android 5.0(Lollypop) and later.

  1. Go to $NDK_ROOT (The topmost folder of NDK zip when unzipped).
  2. Copy $NDK_ROOT/samples/hello-jni directory as $NDK_ROOT/sources/hello-world.
  3. Go to $NDK_ROOT/sources/hello-world.
  4. Edit AndroidManifest.xml to give the application an appropriate name (This is optional).
  5. Go to $NDK_ROOT/sources/hello-world/jni. This is where the source code is.
  6. Edit hello-jni.c, remove all the code, and put in your hello world code. Mine is:
    #include 
    int main( int argc, char* argv[])
    {
        printf("Hello, World!");
        return 0;
    }
  7. Edit Android.mk and change the line include $(BUILD_SHARED_LIBRARY) to include $(BUILD_EXECUTABLE). You can also change the LOCAL_MODULE line to the name you want for your executable(default is hello-jni)
  8. Go back to $NDK_ROOT/sources/hello-world
  9. Run ../../ndk-build to create the executable.
  10. Copy it from $NDK_ROOT/sources/hello-jni/libs/armeabi/hello-jni to /data/local/tmp on the Android device and change it's permissi
answered 2012-04-24T19:40:27.540
12

the "/sdcard" location is not executable, meaning that any file there is not executable at all.

the only way to "adb push" executable would be to put them in "/data/local", which should be writable for adb, and allow execution for anyone.

answered 2012-03-26T07:47:29.650

Your Answer