编译一个不带main()函数的应用程序

【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) 

编译一个不带main()函数的应用程序

源码交代:

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

void func(void)
{
        printf("hello\n");
}

int  my_main(void)
{
        func();

        return 0;
}

编译指令:

  • 因为没有main()函数, 所以编译失败了.
$gcc file.c -o file
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
  • 在这里, 我们指定了用哪个函数替代main()函数.
$gcc -e my_main file.c -nostartfiles -o file

$./file
hello
Segmentation fault (core dumped)

很不幸, 程序无法正常返回(当然, 如果你使用exit()替代return就不会出现问题), 这是因为我们强行指定入口函数且不使用系统默认的应用启动文件导致的. 而使用系统默认的应用启动文件的话, 它将会去找main()函数~

gcc的链接选项:

-nostartfiles
   Do notuse the standard system startup files when linking.  The standard system libraries are used normally, unless -nostdlib or -nodefaultlibs is used.
   链接时不要使用标准系统启动文件。除非使用-nostdlib或-nodefaultlibs,否则通常使用标准系统库。

-nodefaultlibs
   Do not use the standard system libraries when linking.  Only the libraries you specify are passed to the linker, and options specifying linkage of
   the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.  The standard startup files are used normally, unless -nostartfiles is used.
   链接时不要使用标准系统库。只将您指定的库传递给链接器,而忽略指定系统库链接的选项,如-static-libgcc或-share-libgcc。除非使用-nostartfiles,否则通常使用标准启动文件。
   
-nostdlib
   Do not use the standard system startup files or libraries when linking.  No startup files and only the libraries you specify are passed to the
   linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.
   链接时不要使用标准系统启动文件或库。不会将任何启动文件和您指定的库传递给链接器,并且会忽略指定系统库链接的选项,例如-static-libgcc或-share-libgcc。
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安河桥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值