test为可执行程序,libtest为库。在Android中编译并运行它们方法如下,首先要下载NDK。
1. 将库编译为动态库时:
test中仅有一个文件main.c
#include
#include "libtest.h"
staticchars_string[] ="Study hard!";
intmain()
{
printf("%s\n%d\n", s_string, ret8());
return0;
}
Makefile内容如下
BASE_PATH = /home/apuser/Downloads/android-ndk/android-ndk-r4
PATH_PREFIX = $(BASE_PATH)/build/platforms/android-8/arch-arm/usr/
CC = $(BASE_PATH)/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-gcc
LD = $(BASE_PATH)/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-ld
INCLUDES= -I $(PATH_PREFIX)/include \
-I/home/apuser/Downloads/android-ndk/android-ndk-r4/libtest/
CFLAGS = -L $(PATH_PREFIX)/lib
LDFLAGS += -nostdlib -lm -lstdc++ -lc -ldl -Bdynamic -Wl,-dynamic-linker,/system/bin/linker
LDFLAGS += /home/apuser/Downloads/android-ndk/android-ndk-r4/libtest/libtest.so
EXTRA_OBJS = $(PATH_PREFIX)/lib/crtbegin_dynamic.o $(PATH_PREFIX)/lib/crtend_android.o
test: main.c
$(CC) $(CFLAGS) $(INCLUDES) -o $@ $^ $(EXTRA_OBJS) $(LDFLAGS)
clean:
rm -rf test *.o
libtest中有头文件libtest.h和libtest.c
#ifndef _RET_8_H_
#define _RET_8_H_
intret8();
#endif
#include "libtest.h"
intret8()
{
return8;
}
Makefile内容如下
ASE_PATH = /home/apuser/Downloads/android-ndk/android-ndk-r4
PATH_PREFIX = $(BASE_PATH)/build/platforms/android-3/arch-arm/usr/
CC = $(BASE_PATH)/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/arm-eabi-gcc
CCFLAGS = -I$(PATH_PREFIX)/include \
-fpic \
-mthumb-interwork \
-ffunction-sections \
-funwind-tables \
-fstack-protector \
-fno-short-enums \
-D__ARM_ARCH_5__ \
-D__ARM_ARCH_5T__ \
-D__ARM_ARCH_5E__ \
-D__ARM_ARCH_5TE__ \
-Wno-psabi \
-march=armv5te \
-mtune=xscale \
-msoft-float\
-mthumb \
-Os \
-fomit-frame-pointer \
-fno-strict-aliasing \
-finline-limit=64 \
-DANDROID \
-Wa,--noexecstack \
-O2 \
-DNDEBUG \
-g \
LDFLAGS = -nostdlib -Wl,-soname,libtest.so -Wl,-shared,-Bsymbolic -Wl,--whole-archive -Wl,--no-whole-archive -Wl,--no-undefined -Wl,-z,noexecstack -Wl,-rpath-link=$(PATH_PREFIX)lib
EXTRA_OBJS = $(BASE_PATH)/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/../lib/gcc/arm-eabi/4.4.0/libgcc.a $(PATH_PREFIX)/lib/libc.so $(PATH_PREFIX)/lib/libstdc++.so $(PATH_PREFIX)/lib/libm.so
libtest.so: libtest.o
$(CC) $(LDFLAGS) $^ $(EXTRA_OBJS) -o $@
libtest.o: libtest.c
$(CC) $(CCFLAGS) -c $^ -o $@
clean:
rm *.so *.o
启动模拟器后,在Ubuntu的shell中输入
adb push test /data/
adb push libtest /data/
adb shell chmod 777 /data/test
在模拟器的shell中
cd /data/
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH
./test
注意
EXTRA_OBJS = $(BASE_PATH)/build/prebuilt/linux-x86/arm-eabi-4.4.0/bin/../lib/gcc/arm-eabi/4.4.0/libgcc.a
libgcc.a需放在其它库的前面,否则程序在运行时会有无法链接的提示,但在链接时没有报错。