Targeting Android

Is there something special you need to do to target Android? For example:

$ cat test.c
#include <stdio.h>

int main(int argc, char* argv[])
{
    puts("Hello World");
}

$ zig cc -target aarch64-linux-android -o hello test.c
test.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~
1 error generated.

You need the Android SDK at least for creating and signing the apk.

Felix “xq” Queißner in his FOSDEM talk Create an Android Application with Zig shows how to create an Android application using only zig (without java).

An example on how to create a minimal Android app in Zig: Android Template

5 Likes

I’ll take a look at that, but I’m not trying to make an Android application. I’m just trying to compile a binary executable (ideally static) that will run on an Android device using zig cc’s cross compilation features.

You need NDK for C library.

Right, but I’m not sure I understand how to use that with a Zig project or if I even can. I shared a minimal issue above, but I’m trying to zig build -Dtarget=aarch64-linux-android a more complicated project (also involves C code) and I’m not understanding how to do that.

You must specify the path of the NDK stdio.h (<NDK>/sysroot/usr/include), using addIncludePath for zig build or -I for zig cc.
You must also specify the path of the NDK C library (libc) that exports puts (<NDK>/sysroot/usr/lib/aarch64-linux-android/<VERSION>), using addLibraryPath for zig build or -L for zig cc.

2 Likes

Does the C project have any macros for different processors? I have a project that uses C code and runs on Android, I had to create build steps for every single library depended on (so it can easily be built static), so it might not be ideal for larger projects. As far as I know, static executable is your only option if you don’t want to use NDK

And I use aarch64-linux-musl. I’m not sure if the Android libc supports static compilation

1 Like

If you aren’t making it into an application, then how are you planning to run it? Android doesn’t really allow running applications without them being packaged in an APK.

For the record, this isn’t completely true. You can run CLI programs using apps like Termux. It works pretty much like a typical Linux shell. I’ve tested this with basic aarch64 programs.

APKs are definitely the norm, I just wanted to clarify that this is doable.

1 Like