轉:如何在android設備上面跑C或C++程序?

固然,最原始的方法是把你的程序編成靜態的,即編譯時加參數-static便可。但這不符合咱們通常的習慣,也是我沒法容忍的。linux

方法仍是有的:android

一、compilec++

arm-unknown-linux-gnueabi-gcc -o hello hello.c -Wl,-dynamic-linker=/data/app/ld-linux.so.3shell

這樣,編出來的hello就會使用/data/app/ld-linux.so.3看成動態庫加載器app

qj@king:~/test$ readelf -a hello|grep ld-linux
      [Requesting program interpreter: /data/app/ld-linux.so.3]this

二、run, 因爲Android上並無因此須要咱們本身拷貝ld-linux.so.3上去。google

copy ld-linux.so.3 to /data/app.net

copy libc.so.6 to /data/appip

修改LD_LIBRARY_PATH以把咱們的程序所依賴的其它動態庫加入搜索路徑,在adb shell下執行:get

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/data/app

注意,在android下只有data目錄是可寫的,其它目錄都是隻讀的,因此只能用data目錄了。

more info:

-Wl,option
Pass option as an option to the linker. If option contains commas, it is split into
multiple options at the commas. You can use this syntax to pass an argument
to the option. For example, ‘-Wl,-Map,output.map’ passes ‘-Map output.map’
to the linker. When using the GNU linker, you can also get the same effect
with ‘-Wl,-Map=output.map’.

即-dynamic-linker 傳遞給了linker。注意,上面介紹的兩種寫法,一種是等號傳遞;另外一種是逗號傳遞。效果是同樣的。

下面是對鏈接器ld中參數--dynamic-linker的解釋:

#ld --help

  -I PROGRAM, --dynamic-linker PROGRAM
                              Set PROGRAM as the dynamic linker to use

ld-linux.so.三、libc.so.6等是從toolchains下面拷來的。

實際上ld-linux.so.3是指向ld-2.9.so的連接,因此實際上須要把ld-2.9.so拷貝到/data/app目錄下,而後作一個連接:

ln -s ld-2.9.so ld-linux.so.3

雖然ld-2.9.so看上去是個動態庫,但實際上它是可執行的。加載它會被執行,因此須要給它增長可執行權限,不然執行時會提示說not found 之類的,總之android shell下的這個提示很難讓人理解:

chmod 777 ld-2.9.so

chmod 777  ld-linux.so.3

若是你的代碼是C++寫的,編譯須要使用arm-...linux...-g++,並且運行時還須要把libstdc++.so.6拷貝到/data/app目錄下去。

另外,還有一個關鍵點:

必定要把/data/app加入到LD_LIBRARY_PATH環境變量中。

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/data/app

以上步驟完成後,基本能夠保證能成功運行,已經通過了個人屢次驗證。

 參考資料:https://groups.google.com/forum/?fromgroups=#!topic/android-internals/fHKKNkdPvAU

相關文章
相關標籤/搜索