Jan 23, 2013

編譯Nethack for Android筆記


一直以來都對NETHACK很有興趣,發現有ANDROID的版本時,更是好奇如何將以C語言寫成的程式移植到以JAVA為主的ANDROID平台。
關於移植上的重點,我想應該非JNI莫屬,JNI提供一個界面,提供由NDK編譯出Shared Object有機會可以直接在ANDROID APP中使用。
這次的目的是要紀錄如何成功編譯NETHACK for ANDROID。

專案的網站為

因此先將原始碼checkout下來:
svn checkout http://nethack-android.googlecode.com/svn/trunk/ nethack-android-read-only

直接閱讀編譯ANDROID版本的README
vim ./nethack-3.4.3/sys/android/README

以下節錄編譯時的重要步驟:
1. Unpack the source tree somewhere.
# 這部份已經完成了

2. Open 'sys/android/setup.sh' in a text editor, and change ANDROID_NDK_DIR to indicate the path where you have installed the Android NDK.
# 由於需要用到c/c++ compiler編譯nehack的原始碼,在這裡要設定NDK的目錄
ANDROID_NDK_DIR=/opt/android-ndk-r8b

3. Verify options in 'include/config.h' and elsewhere, if you want anything different than the standard configuration.
# 在這裡基本上不需要特別針對config.h做特別的修改,文件中雖然#define ANDROID是註解,但makefile中會自動加上。

4. Run Eclipse and create a new project, importing the source code from 'sys/android/NetHackApp'.
# 在Eclipse中匯入APP的專案:File -> Import… -> Android -> Existing Android Code Into Workspace

5. Make 'sys/android' your current directory, and run 'setup.sh'. This should create some symbolic links and do other preparations to make your source tree ready to build the Android port.
# 在執行setup.sh前,請先在NDK的目錄中新增apps目錄:mkdir ${ANDROID_NDK_DIR}/apps
# 如果發生設定的錯誤時,可以執行sh ./setup_clean.sh && sh ./clean.sh清空產生的檔案

6. Go to the 'dat' folder, and type 'make'. This builds the data files, using tools built for the host computer.
# 照步驟作即可

7. Go to your NDK directory (as specified as ANDROID_NDK_DIR).
# 照步驟作即可

8. Type 'make APP=NetHackNative' to build the native code.
# 在編譯的最後要進行shared library的link時,遇到以下錯誤:
SharedLibrary  : libnethack.so
./out/apps/NetHackNative/armeabi/objs/nethack/__/sys/share/unixtty.o: In function `init_linux_cons':
/Users/leeweilun/Desktop/VBShare/src/android_app_src/nethack-android-read-only/nethack-3.4.3/sys/android/NetHackNative/nethack/../sys/share/unixtty.c:429: undefined reference to `has_colors'
collect2: ld returned 1 exit status
make: *** [out/apps/NetHackNative/armeabi/libnethack.so] Error 1
# 發現是在./sys/shared/unixtty.c中,有用到curses library的has_colors(),
# 我自己的解法是在unixtty.c中加入#undef TEXTCOLOR,使得這段code不會被編譯到
# 重新在執行一次make就成功了,也會將libnethack.so複製到APP的project中。

9. Go back to Eclipse, build and launch the application.
# 接下來應該可以正常編譯並將APP(APK)安裝到Android系統上了。

以上就是這次編譯的過程。


No comments: