Home » Android » NDK / Middleware / HAL » Cross compiling C/C++ programs for Android using NDK Toolchains

Cross compiling C/C++ programs for Android using NDK Toolchains

If you are using NDK version more than r19, the toolchains which comes as part of NDK zip can be used and we no longer need to generate toolchain using script make-standalone-toolchain.sh for versions before r19. Below post will describe how we can compile native C/C++ programs using NDK.

The first step is to make sure you have installed NDK by following our article at “How to install Android NDK on Ubuntu 16.04 / 18.04” By the time of writing this article Android NDK version was r20, so below section of compiling C programs for Android using NDK version more than r19 is most suitable for you.

Compiling C/C++ programs for Android using NDK version more than r19

Lets write a simple helloworld program as,

#include <stdio.h>

int main(int argc, char **argv) {
        printf("Hello world from Android");
        return 0;

Assuming you have installed Android NDK at /home/myuser/android_ndk/android-ndk-r20/ [Your version might be more than r20] , export the toolchain path as below,

$ export PATH=$PATH:/home/myuser/android_ndk/android-ndk-r20/toolchains/llvm/prebuilt/linux-x86_64/bin

Now, connect your device using adb and verify what is the processor type using adb command as,

$ adb shell cat /proc/cpuinfo | grep Processor
Processor	: AArch64 Processor rev 4 (aarch64)

As you can see above, our Android device is 64 bit ARM processor, hence we will use related clang command as below,

$ aarch64-linux-android29-clang -o helloworld helloworld.c 
$ file helloworld
helloworld: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /system/, not stripped

Now, you can push this executable helloworld to your Android device for verifying the result.

Compiling C/C++ programs for Android using NDK less than r19

For NDK versions below r19, we have to generate the toolchain using make-standalone-toolchain.sh script as,

$ bash ./android_ndk/android-ndk-r20/build/tools/make-standalone-toolchain.sh --arch=arm64 --install-dir=./android_toolchain/

Toolchain installed to ./android_toolchain/.

As you can see above, make-standalone-toolchain.sh script generates the toolchain at android_toolchain directory present in your current working directory. The tools required to compile C/C++ programs resides in android_toolchain/bin/ directory and we can export the path same as we did above,

$ export PATH=$PATH:/home/myuser/android_toolchain/bin/

Now, you can compile the C program as,

$ aarch64-linux-android29-clang -o helloworld helloworld.c

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment