Android.bp
cc_binary {
name: "my_native_bin",
srcs: ["main.cpp"],
cflags: [
"-Wall", // 启用标准警告
"-Werror", // 将警告视为错误
"-fPIE", // 生成位置无关代码
"-pie", // 链接为位置无关可执行文件
],
shared_libs: ["liblog"], // 依赖库
stl: "c++_static", // 静态链接 C++ 标准库
}
main.cpp
#include <stdio.h>
#include <android/log.h> // 需链接liblog
int main() {
printf("Hello from Native!\n");
__android_log_print(ANDROID_LOG_INFO, "MyApp", "Log from NDK");
return 0;
}
执行
adb push out/target/product/crosshatch/system/bin/my_native_bin system/bin/
adb shell
./my_native_bin
Hello from Native!
adb logcat -b all|grep MyApp
04-21 17:11:52.510 23304 23304 I MyApp : Log from NDK
总结
可以在最简单的Native二进制程序里面实现更复杂的逻辑,加深对Android组件的理解。