How do I build a native (command line) executable to run on Android?

前端 未结 4 596
囚心锁ツ
囚心锁ツ 2020-11-28 21:04

I\'ve had success with building an Android app (GUI) that uses a native (JNI) library.

However, now I would like to create an executable that runs from the command l

4条回答
  •  独厮守ぢ
    2020-11-28 22:00

    Here's an example project that follows the KennyTM's answer. You can create it from scratch or modify another project, for example, hello-jni in the NDK samples.

    jni/main.c:

    #include 
    int main() {
        printf("hello\n");
        return 0;
    }
    

    jni/Application.mk:

    #APP_ABI := all
    APP_ABI := armeabi-v7a
    

    jni/Android.mk:

    LOCAL_PATH := $(call my-dir)
    
    # first target: the hello-jni example
    # it shows how to build multiple targets
    # {{ you may comment it out
    include $(CLEAR_VARS)
    
    LOCAL_MODULE    := hello-jni
    LOCAL_SRC_FILES := hello-jni.c
    LOCAL_LDLIBS := -llog -L$(LOCAL_PATH)/lib -lmystuff # link to libmystuff.so
    
    include $(BUILD_SHARED_LIBRARY)
    #}} you may comment it out
    
    
    # second target
    include $(CLEAR_VARS)
    
    LOCAL_MODULE := hello
    LOCAL_SRC_FILES := main.c
    
    include $(BUILD_EXECUTABLE)    # <-- Use this to build an executable.
    

    I have to note that you will not see any logging in the stdout output, you will have to use adb logcat to see it.

    So if you want logging:

    jni/main.c:

    #include 
    #include 
    int main() {
        printf("hello\n");
        __android_log_print(ANDROID_LOG_DEBUG  , "~~~~~~", "log %i", 0); // the 3rd arg is a printf-style format string
        return 0;
    }
    

    and the corresponding section in jni/Android.mk becomes:

    LOCAL_PATH := $(call my-dir)
    
    #...
    
    include $(CLEAR_VARS)
    
    LOCAL_MODULE := hello
    LOCAL_SRC_FILES := main.c
    LOCAL_LDLIBS := -llog   # no need to specify path for liblog.so
    
    include $(BUILD_EXECUTABLE)    # <-- Use this to build an executable.
    

提交回复
热议问题