【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)
编译一个不带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。
本文探讨了在不包含main()函数的情况下,如何通过GCC编译器成功编译并运行C程序。文章详细介绍了编译指令及链接选项,如-em替代main函数、-nostartfiles避免使用默认启动文件,以及由此产生的程序运行问题。
1万+

被折叠的 条评论
为什么被折叠?



