Linux执行c的可执行文件,c编译成可执行文件在linux上运行

平台是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

int main(int argc, char* argv[])

//argc是命令行运行时输入的参数个数,argv是参数字符串数组,argv[0]是应用名称

{

int i=0;

printf("argc=%d\n",argc);

for(i=0; 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即可。

本文同步分享在 博客“krokodil98”(CSDN)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值