Compile c/c++ for android and make a native executable

Compile c/c++ for android and make a native executable.
Most of us are familiar with android studio or Android SDK to develop an Android App but what about binary executables?
Let say you have a C code like this and you what to compile it and run it on your Android phone just like a console application.

#include <stdio.h>
int main()
{
 printf("Hello world \n");
 printf("I'm running on Android\n");
 return 0;
}

First of all, you need to get the compiler using this command:

sudo apt-get update
sudo apt-get install build-essential
sudo apt-get install gcc-arm-linux-gnueabihf

We assume your Android phone has an ARM Cpu that most of them have.
It downloads and installed an ARM c Compiler that helps you to get your codes compiled on an x86 host and make an ARM executable binary.
Do we need an IDE? well, it makes it easier but our point here is getting familiar with the build system too. So no you just need text editor just like GEdit.

Ok now make an empty file and name it hello.c or whatever-you-like.c.
Now open a terminal in the same folder and enter this command:

arm-linux-gnueabi-gcc -static -march=armv7-a hello.c -o hello

It makes a file named hello (or whatever you named it) under the same folder. That’s it your executable binary is ready you just need to transfer it to your cell phone.
You can use ADB push command or any other method.
Now you can run it from ADB shell or an android terminal with a command like this:

 ./hello

The result would be something like this:

Or even you own app with a command like this:

Process process = Runtime.getRuntime().exec("/sdcard/yourfolder/[filename]");

keep it in your mind that you may need to give executable permission to the binary file using a command like this:

 chmod +x hello 

or

chmod 777 hello // be careful with this one! use it ONLY for testing!


Setting 777 permissions to a file or directory means that it will be readable, writable, and executable by all users and may pose a huge security risk.

Congratulation! you did it! 😀 Easy, Right? But wait there is more; If you are interested in combining and integrating c++ with your java App, You can also check at https://developer.android.com/ndk/guides