平台是ubuntu20.04。
还是那个超级简单的例子,在android上的编译和运行可看之前文章:c交叉编译成可执行文件在android上运行
因为突然想到android那篇忘记涉及到执行C程序时传命令行参数这部分,又想到linux和android上的C程序编译和运行又并不完全一样,故而有了这篇。
实验步骤:
新建文件夹hello:
创建hello.c和makefile。
test@test-Vostro-3268:~/wahaha/hello$ ls
Makefile hello.c
hello.c内容:
#include <stdio.h>
int main(int argc, char* argv[])
//argc是命令行运行时输入的参数个数,argv是参数字符串数组,argv[0]是应用名称
{
int i=0;
printf("argc=%d\n",argc);
for(i=0; i<argc; i++){
printf("argv[%d] = %s\n", i+1, argv[i]);
}
printf("hello world\n");
printf("goodbye\n");
return 0;
}
makefile内容:
hello: hello.o
default:
gcc -c hello.c
gcc -o hello hello.o
clean:
rm hello hello.o
install:
sudo cp hello /sbin
编译时的输出:
(如果不sudo make install,则调用该程序时,需要在~/wahaha/hello
下的终端里输入./hello test 123
才可执行)
test@test-Vostro-3268:~/wahaha/hello$ make
cc -c -o hello.o hello.c
cc hello.o -o hello
test@test-Vostro-3268:~/wahaha/hello$ make clean
rm hello hello.o
test@test-Vostro-3268:~/wahaha/hello$ make
cc -c -o hello.o hello.c
cc hello.o -o hello
test@test-Vostro-3268:~/wahaha/hello$ sudo make install
[sudo] password for test:
sudo cp hello /sbin
test@test-Vostro-3268:~/wahaha/hello$
运行效果:
//只要cp到了/sbin中,任何文件夹位置的终端里均可调用该程序。
test@test-Vostro-3268:~/wahaha$ hello test 123
argc=3
argv[1] = hello
argv[2] = test
argv[3] = 123
hello world
goodbye
test@test-Vostro-3268:~/wahaha$
在android平台上的命令行传参也是同样的,第一个int变量是参数个数,第二个是参数数组。这样就可以在main函数里对命令行参数进行利用了。
关于这部分具体实现的原理,之后会抽时间单写一篇源码分析。
PS:注意一下生成出来的可执行文件hello的权限,可ls-l hello查看。如果没有执行的权限,会报错permission denied。这时候只需要chmod 777 hello即可。