Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實戰技巧:Hello, Native! 在裝置上跑一顆 C 程式

編輯:關於 Android 程式設計

對做上層 App 的人來說,在 Android 上直接執行 C 程式顯得有點陌生,畢竟應用層開發繞不開 Java。但對底層驅動工程師而言這是家常便飯——Android 是 Linux 的分支,底層世界說的語言本來就是 C/C++。偶爾為了驗證某個功能,我們確實需要寫一支直接跑在 Android 終端下的原生程式,前提是你手上有交叉編譯工具,以及機器的 root 權限。

一、把交叉編譯工具從 NDK 裡剝出來

NDK 為 native 開發做了很多事,但我們其實只需要其中的交叉編譯器。以 64 位元 Ubuntu 14.04 為例,下載對應版本的 NDK(android-ndk-r10e-linux-x86_64.bin)後,先給執行權限再解開:

$ chmod a+x android-ndk-r10e-linux-x86_64.bin
$ ./android-ndk-r10e-linux-x86_64.bin

接著用 NDK 內附的腳本,生成一份獨立的 toolchain:

$ ./build/tools/make-standalone-toolchain.sh \
    --platform=android-19 \
    --toolchain=arm-linux-androideabi-4.9

Copying prebuilt binaries...
Copying sysroot headers and libraries...
Copying c++ runtime headers and libraries...
Creating package file: /tmp/ndk-linc/arm-linux-androideabi-4.9.tar.bz2
Cleaning up...
Done.

找個合適的位置解壓出來即可:

build-tools$ tar jxvf arm-linux-androideabi-4.9.tar.bz2

二、hello, native

寫一支最經典的 main_test.c:

#include <stdio.h>

int main() {
    printf("just a test, linc! hello, native!\n");
    return 0;
}

用剛剛產生的 gcc 編譯,然後推到裝置上執行:

$ ~/bin/build-tools/arm-linux-androideabi-4.9/bin/arm-linux-androideabi-gcc \
    -o main_test main_test.c

$ adb push main_test /data/app
$ adb shell
root@hammerhead:/ # cd data/app
root@hammerhead:/data/app # ./main_test
just a test, linc! hello, native!

如我們所願,它就跟在 Linux 上一模一樣地跑起來了。

三、編譯多檔案專案

接著試試兩個檔案的情形。shooter.c 提供一個氣泡排序與取得最小值的方法:

#include "shooter.h"
#include <stdio.h>

void bubble_sort(int *array, int n) {
    int i, j, tmp;
    for (i = 0; i < n - 1; i++)
        for (j = n - 1; j > i; j--)
            if (array[j - 1] > array[j]) {
                tmp = array[j - 1];
                array[j - 1] = array[j];
                array[j] = tmp;
            }
}

int A(int a) {
    int n = 10, i;
    int array[] = {54, 12, 346, 5, 23, 67, 234, 324, 45, 98};
    bubble_sort(array, n);
    for (i = 0; i < n; i++) printf("%d, ", array[i]);
    printf("\nA result: %d\n", array[0]);
    return array[0];
}

shooter_tester.c 負責呼叫:

#include <stdio.h>
#include "shooter.h"

int main() {
    int result = A(0);
    printf("A result: %d\n", result);
    return 0;
}

多檔案只要把來源一起丟給編譯器:

$ ~/bin/build-tools/arm-linux-androideabi-4.9/bin/arm-linux-androideabi-gcc \
    -o test shooter_tester.c shooter.c
$ adb push test /data/app/
$ adb shell
root@hammerhead:/data/app # ./test
54, 12, 346, 5, 23, 67, 234, 324, 45, 98,
A result: 5

四、加上隨機數

把原本的固定陣列換成 rand() 產生,於是每次執行結果都不同。這裡踩到一個經典的錯誤:

error: undefined reference to 'srand'
error: undefined reference to 'rand'

原因很單純:隨機數的函式宣告在 stdlib.h 而不是 time.h,補上 #include <stdlib.h> 就解決了。編譯執行後可以看到每次都拿到不同的序列:

$ ./test
18, 95, 91, 55, 13, 37, 74, 85, 83, 66,
A result: 13

$ ./test
59, 100, 84, 32, 26, 46, 11, 50, 44, 83,
A result: 11

結語

從這一刻起,你大可以把 Android 當成一台 Linux 來玩。剩下的就交給你的想像力了,祝你愉快!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved