Linux程序移植到Android

来源:互联网 发布:智慧养羊软件 编辑:程序博客网 时间:2024/06/08 15:25

转自http://www.linuxidc.com/Linux/2011-05/35556.htm

http://www.linuxidc.com/Linux/2014-03/97499.htm

移植,最主要是从 一个平台移植到另一个平台。所以移植前我们要知道目标机器的架构,对于手机,可用如下命令:

www.linuxidc.com@linuxidc-laptop:~/test$ adb shell
# cd proc

# cat cpuinfo
Processor    : ARM926EJ-S rev 5 (v5l)
BogoMIPS    : 284.26
Features    : swp half thumb fastmult vfp edsp java 
CPU implementer    : 0x41
CPU architecture: 5TEJ
CPU variant    : 0x0
CPU part    : 0x926
CPU revision    : 5

Hardware    : Goldfish
Revision    : 0000
Serial        : 0000000000000000

这里我们可以清楚的知道,我们的手机的架构为Processor    : ARM926EJ-S rev 5 (v5l),所以为arm的。

那我们写个hello world 吧,


root@xiaowen-laptop:/home/xiaowen/test# arm-none-linux-gnueabi-gcc -static  hello.c -o hello

www.linuxidc.com@linuxidc-laptop:~/test$ adb push hello data/hello

www.linuxidc.com@linuxidc-laptop:~/test$ adb shell
# cd data
# ls
hello
misc
local
app-private
backup
property
anr
app
data
dontpanic
dalvik-cache
system
lost+found
# hello
hello: not found
# ./hello
hello world#

由于本人还是比较偏重于先说明原理在说明实际操作步骤,要知其然更要知其所以然,如下图所示:

Linux程序移植到Android上

传统的linux系统中的程序基本都依赖于glibc(至于什么是glibc可以百度去),而右边AOSP(Android Open-Source Project)的程序基本都是依赖于Bionic(由谷歌公司开发类库,用来替代glibc)。这就决定了要想移植linux上的程序到android上就必须解决这个依赖的类库不同的问题。

一般情况下,有两种方法。

一个就是将程序静态编译,将程序中所有需要的库全部编译进可执行文件中。这样程序在android中运行就不需要链接任何动态库了。但是带来一个非常大的弊端就是这个程序会非常大,资源利用会非常低下。一个简单的helloWorld!都可以达到好几百k!

另一个就是用ld-llinux.so.3来替代android系统中/system/bin/linker来作为链接器进行动态链接,当然这就需要将相应的动态库也拷贝到android中(个人理解,如果表述不够准确请指正)。这样就可以进行动态链接,并且正常运行了。

静态编译方法:

首先我们以移植一个helloworld程序作为例子。

#include<stdio.h>

void main()

{

printf("HelloWorld!\n");

}

输入命令进行静态编译:arm-none-linux-gnueabi-gcc hello.c -static -o hello.out

然后利用adb push 将helllo.out放进android设备的/system/bin目录中,

用chmod 755 /system/bin/hello.out 更改其为执行权限。

输入: hello.out 即可看到屏幕上输出HelloWorld!

如上说所一样,这个hello.out程序有近650k,而且其使用的代码不可重用。

动态链接方法:

动态链接依旧按照上述helloworld程序作为例子。

编译命令为:arm-none-linux-gnueabi-gcchello.c -ohello.out -Wl,-dynamic-linker=/system/lib/ld-linux.so.3

这里需要说明的是,这个/system/lib是指android手机中存放连接器ld-linux.so.3的目录。正式利用这个连接器来替代android系统中/system/bin/linker才能动态链接运行程序。

编译完成后,可以输入命令 readelf -d hello.out 来查看它的动态链接库有哪些。比如这个helloworld程序的动态链接库如下图所示:

Linux程序移植到Android上

可以看到libgcc_s.so.1和libc.so.6就是这个helloworld所需要的动态链接库。

然后找到arm-none-linux-gnueabi-gcc的安装目录。如果你是解压压缩包配置path的安装路径的话,这些动态链接库文件就在./arm-none-linux-gnueabi/libc/armv4t/lib 下。

找到ld-linux.so.3和上述需要的动态链接库,将他们cp 出来。

然后,利用adb push 将他们放入android系统的/system/lib目录下,将hello.out放入到/system/bin下,更改hello.out和ld-linux.so.3的权限为可执行即可(chmod 755 hello.out)。这里需要说明一下,ld-linux.so.3作为他们的连接器,一定需要可执行权限,否则就会提示permission denied。

做好这些后,输入hello.out 即可看到屏幕打出helloworld!


0 0