│ └── main.c
main.c :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int var1 = 111;
int var2 = 222;
int sum = 0;
sum = var1 + var2;
printf("sum is: %d\n", sum);
return 0;
}
(1) build with ndk-build
Android.mk :
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := ndk-sample
LOCAL_SRC_FILES := main.c
LOCAL_CFLAGS += -pie -fPIE
LOCAL_LDFLAGS += -pie -fPIE
include $(BUILD_EXECUTABLE)
红色标识的这两条语句,必须要有,否则,编译生成的二进制可执行文件在Android设备中执行时,会提示
# ndk-sample
error: only position independent executables (PIE) are supported.
这样的错误,加上红色标识的这两句,则不会有这个问题。
编译的二进制可执行文件执行时:
# ./ndk-sample
sum is: 333
(2) build with arm-linux-androideabi-gcc
$ arm-linux-androideabi-gcc -v
Using built-in specs.
COLLECT_GCC=arm-linux-androideabi-gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-androideabi/4.7.3/lto-wrapper
Target: arm-linux-androideabi
Configured with: ../src/configure --prefix=/usr --libexecdir=/usr/lib --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=arm-linux-androideabi --with-build-sysroot=/build/buildd/gcc-arm-linux-androideabi-0.20130705.1/sys-root --disable-multilib --with-gnu-as --with-gnu-ld --enable-languages=c,c++ --disable-ppl-version-check --disable-cloog-version-check --enable-cloog-backend=isl --disable-libssp --disable-nls --disable-libmudflap --disable-shared --disable-sjlj-exceptions --disable-libquadmath --disable-libitm --disable-libatomic --with-float=soft --with-fpu=vfp --with-arch=armv5te --enable-target-optspace --disable-docs --disable-nls --enable-threads --enable-tls --enable-libgomp --disable-libitm --disable-libatomic --disable-libstdc__-v3
Thread model: posix
gcc version 4.7.3 (Linaro GCC 4.7-2014.01)
通过这种方式编译二进制可执行文件时,也需要 -pie -fPIE 的标识,否则依旧会提示:
error: only position independent executables (PIE) are supported.
这样的错误,增加这两个标识后,生成二进制可执行文件,在Android设备中执行二进制可执行文件,
收到:
# ./main
WARNING: linker: ./main has text relocations. This is wasting memory and prevents security hardening. Please fix.
sum is: 333
执行结果是正确的,但是text relocations是什么问题呢? 待检查解决???