简体   繁体   中英

Compile and run C code for Android

I would like to create any run-able file from simple C code that would be able to run in the libraries level of Android. I'm new to Android and all what I found till now is the option to use the NDK which requires java code also - and it runs the application in the applications level - and I want it to run as a system command line(Is it possible?) file.

You can try to compile your code to executable, and then directly launch it from ADB shell. Basically, when you compile your code (assume you have a cpp file called hello.cpp ) using ndk-build, write your Android.mk like this:

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \
        hello.cpp

LOCAL_MODULE:= hello
include $(BUILD_EXECUTABLE)

Then you can use ADB tool to help you push the executables into your device, and run it via adb shell, for example,

adb shell "mkdir -p /data/test"
adb push hello /data/test/
adb shell "cd /data/test & chmod 777 hello & ./hello"

The above method requires you to have root permission, otherwise you cannot chmod or launch the native executable.

There is a tool called Android Native Program Launcher , which allows you to run native code in a un-rooted device, you can give it a try.

Another way to push the executable binary to /data/local/tmp/ folder, and you will have full control over the executable as well. `adb push you_binary /data/local/tmp/

Let's start from the bottom up.

Going C (or C++) does not grant your code extra rights under Android.

There are different options of doing all your development without Java. There are frameworks for pure C++ (like NativeActivity), or for C# (MonoDroid), or Scala, or Ruby, or whatnot.

Android NDK also allows to simply build an executable - one that can be run from command line, and has no GUI. Your Android app can launch such executable via standard Java Runtime.exec() and her siblings. Or you can launch this executable from a terminal emulator or adb shell .

If you have root access on your device (or if you flash your own mod), you can launch an executable through the standard Linux init.rc or similar.

Note that in the latter case, you can easily grant your executable root or other permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM