简体   繁体   中英

How to compile and run a simple C code for Android?

Here is the basic C source code:

#include <stdio.h>
int main(void) {
    puts("hello world!");
    return 0;
}

I am able to compile for Android with NDK toolchain with:

aarch64-linux-android21-clang test.c

It generates an a.out file that I transfer to the Android device with:

adb push a.out /data/local/tmp
adb shell chmod 777 /data/local/tmp/a.out

When I try to run it with:

adb shell /data/local/tmp/a.out

I have the message: "/system/bin/sh: /data/local/tmp/a.out: No such file or directory"

What am I doing wrong?

you can use this nodejs script to automate build and test your c/c++ program for android

 let cpp=`
#include<iostream>
#include<string> 
using namespace std;
int main(){
  cout<<"hellow word"<<endl; 
  return 0;
}
` 
let args=['--target=armv7a-linux-androideabi23']
let cpu="armeabi-v7a" 
wfs('test.cpp',cpp)
args.push("test.cpp")     
 args.push("-static-libstdc++")
 //in case you want to build sharedlib uncomment next line
 //args.push("-shared")

lg=run(runners.clang,args)

lg=run(runners.adb,'push a.out /data/local/tmp/a.out')

//in case -static-libstdc++ not used uncomment next line;
//copy c++_shared to same dir where to a.out
//run(adb,'push c++_shared.so /data/local/tmp/c++_shared.so')
 
let shellcmd=[];
shellcmd.push("cd /data/local/tmp")
//in case -static-libstdc++ not used uncomment next line;
// shellcmd.push("export LD_LIBRARY_PATH=.")
shellcmd.push("chmod +x a.out")  
shellcmd.push("./a.out")  
// a.out excution result
let output=run(runners.adb,`shell "${shellcmd.join("&&")}"`)
lg(output)








            //++++++++++utilis++++++++++
            function lg(...args){
            console.log(...args)
            }

            function run(cmd,args){
            if(args) cmd= cmd+" "+args.join(" ");
            return require('child_process').execSync(cmd);
            }

            function wfs(p,data){
            require("fs").writeFileSync(p,data)
            }

In my case, I had to use "armv7a-linux-androideabiXX-clang" for compilation and then it is ok. XX must be replaced by the API version.

On my windows system, clang binaries and scripts are in the folder "D:\AndroidSdk\ndk\21.1.6352462\toolchains\llvm\prebuilt\windows-x86_64\bin"

The most recent script that can be used is "armv7a-linux-androideabi29-clang++.cmd" and it is ok for compiling C sourcecodes for running on Samsung A3 phones in my case.

I think this is because this is not a 64-bit kernel and I figured that out after Eugene Sh asked me in comments to this question (if he adds an answer then I'll accept it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM