編譯
1. 下載安裝 Android NDK,不必贅述。假定我們安裝到了 /Developer/android-ndk-r4b/.
2. 在工作目錄下建立一個 jni
目錄。如果要使用 NDK 內建的 Android.mk,必須叫做這個名字,否則 make 的時候會找不到檔案,錯誤提示可能類似下面:
Android NDK: Could not find application project directory !<br />Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.<br />/Developer/android-ndk-r4b/build/core/build-local.mk:85: *** Android NDK: Aborting . Stop.<br />
把程式源碼放到這個目錄。假定程式的名字是 hello.c,那麼目錄結構為
<Project>/jni/hello.c
3. 從 NDK 的 sample 裡複製一份 Android.mk 到 jni 目錄。因為我們編譯的是 Native App 可執行程式而不是 JNI lib,所以需要修改 Android.mk,把 include $(BUILD_SHARED_LIBRARY
) 改成 include $(BUILD_EXECUTABLE
).
這裡給出樣本的 Android.mk 檔案內容:
<br /># Copyright (C) 2009 The Android Open Source Project<br />#<br /># Licensed under the Apache License, Version 2.0 (the "License");<br /># you may not use this file except in compliance with the License.<br /># You may obtain a copy of the License at<br />#<br /># http://www.apache.org/licenses/LICENSE-2.0<br />#<br /># Unless required by applicable law or agreed to in writing, software<br /># distributed under the License is distributed on an "AS IS" BASIS,<br /># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br /># See the License for the specific language governing permissions and<br /># limitations under the License.<br />#<br />LOCAL_PATH := $(call my-dir)<br />include $(CLEAR_VARS)<br />LOCAL_MODULE := hello<br />LOCAL_SRC_FILES := hello.c<br />#include $(BUILD_SHARED_LIBRARY)<br />include $(BUILD_EXECUTABLE)<br />
4. 在 <Project> 目錄中運行 /Developer/android-ndk-r4b/ndk-build. 如果編譯沒有錯誤,那麼輸出為:
Compile thumb : hello <= <Project>/jni/hello.c<br />Executable : hello<br />Install : hello => <Project>/libs/armeabi
那麼,我們需要的可執行檔就在 libs/armeabi 目錄下了。可以用 adb push 上傳到手機或者模擬器中運行測試。