按:可能是由于性能的问题,也有可能是由于版权的问题,Android使用bionic而不是gnu libc/uclibc,这使得很多native code的移植起来比较困难。这里转一篇如何做动态编链的文章。
在另外一个帖子中,neil已经介绍了如何编译一个静态的native程序在Android中运行,本文主要说明如何编译动态链编的native程序。
编译环境要求:下载Android的源码,并执行完一次完整的编译。以下的所有命令均是在编译后的源码根目录下执行。
1. 编译C code
同样以hello.c为例:
#include <stdio.h> #include <stdlib.h>
int main() { printf("hello, world!\n"); return 0; }
|
执行以下步骤生成动态链编的binary文件:
- 生成目标文件:prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-gcc -I bionic/libc/arch-arm/include -I bionic/libc/include -I bionic/libstdc++/include -I bionic/libc/kernel/common -I bionic/libc/kernel/arch-arm -include system/core/include/arch/linux-arm/AndroidConfig.h -c -o hello.o hello.c
- 生成可执行程序:prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-gcc -nostdlib -Bdynamic -Wl,-T,build/core/armelf.x -Wl,-dynamic-linker,/system/bin/linker -Wl,--gc-sections -Wl,-z,nocopyreloc -o hello -Lout/target/product/generic/obj/lib -Wl,-rpath-link=out/target/product/generic/obj/lib -lc -lstdc++ out/target/product/generic/obj/lib/crtbegin_dynamic.o hello.o -Wl,--no-undefined ./prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/../lib/gcc/arm-eabi/4.2.1/interwork/libgcc.a out/target/product/generic/obj/lib/crtend_android.o
用命令file查看生成的hello文件属性:
hello: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), stripped
可以证明此时的hello是一个动态链编的文件。
2. 编译native c++ 代码
以hello_cpp为例:
hello_cpp.h #ifndef HELLO_CPP_H #define HELLO_CPP_H
class Hello { public: Hello(); ~Hello(); void printMessage(char* msg); };
#endif
hello_cpp.cpp #include <stdio.h> #include "hello_cpp.h"
Hello::Hello() { }
Hello::~Hello() { }
void Hello::printMessage(char* msg) { printf("C++ example printing message: %s", msg); }
int main(void) { Hello hello_obj; hello_obj.printMessage("Hello world!\n"); return 0; }
|
执行以下命令完成:
- 编译目标文件:prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-g++ -I bionic/libc/arch-arm/include -I bionic/libc/include -I bionic/libstdc++/include -I bionic/libc/kernel/common -I bionic/libc/kernel/arch-arm -include system/core/include/arch/linux-arm/AndroidConfig.h -fno-exceptions -fno-rtti -c -o hello_cpp.o hello_cpp.cpp
- 编译可执行程序:prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-g++ -nostdlib -Bdynamic -Wl,-T,build/core/armelf.x -Wl,-dynamic-linker,/system/bin/linker -Wl,--gc-sections -Wl,-z,nocopyreloc -o hello_cpp -Lout/target/product/generic/obj/lib -Wl,-rpath-link=out/target/product/generic/obj/lib -lc -lstdc++ out/target/product/generic/obj/lib/crtbegin_dynamic.o hello_cpp.o -Wl,--no-undefined ./prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/../lib/gcc/arm-eabi/4.2.1/interwork/libgcc.a out/target/product/generic/obj/lib/crtend_android.o
同样用file查看hello_cpp的文件属性:
hello_cpp: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), stripped
但是很不幸的是,android自带的toolchain不支持C++标准库的开发,即所有的std namespace下的类均无法使用,包括基本的string。
阅读(2605) | 评论(0) | 转发(0) |