在C中没有main()的情况下编译并运行程序 [英] Compile and run program without main() in C
问题描述
我试图在 C
中没有 main()
函数的情况下编译和运行下面的程序。我已经使用以下命令编译了我的程序。
gcc -nostartfiles nomain.c
并且编译器发出警告
/ usr / bin / ld:警告:找不到入口符号_start;默认为0000000000400340
好的,没问题。然后,我运行可执行文件(a.out), printf
语句都成功打印,然后得到段错误。
所以,我的问题是,为什么在成功执行打印语句后出现分段错误?
我的代码:
#include< stdio.h>
void nomain()
{
printf(Hello World ... \\\
);
printf(没有main ... \\\
成功运行);
}
输出:
Hello World ...
没有main的成功运行...
分段错误(核心转储)
注意:
这里, -nostartfiles
gcc标志可以防止编译器在链接时使用标准启动文件
让我们看一下程序生成的程序集:
.LC0:
.stringHello World ...
.LC1:
.string
nomain:
push rbp
mov rbp,rsp
mov edi,OFFSET FLAT:.LC0
call puts
mov edi,OFFSET FLAT:.LC1
call puts
nop
pop rbp
ret
请注意 ret
语句。你的程序的入口点被确定为 nomain
,这一切都很好。但是,一旦函数返回,它将尝试跳入调用堆栈中的地址,该地址未被填充。这是一个非法访问,并出现分段错误。
一个快速解决方案是在 exit()
(假设C11,我们也可以将函数标记为 _Noreturn
):
#include< stdio.h>
#include< stdlib.h>
_Noreturn void nomain(void)
{
printf(Hello World ... \\\
);
printf(没有main ... \\\
成功运行);
exit(0);
$ / code>
事实上,现在你的函数的行为与常规的<$ c $非常相似c> main 函数,因为从 main
返回后,出口
函数被调用 main
的返回值。
I'm trying to compile and run following program without main()
function in C
. I have compiled my program using the following command.
gcc -nostartfiles nomain.c
And compiler gives warning
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400340
Ok, No problem. then, I have run executable file(a.out), both printf
statements print successfully, and then get segmentation fault.
So, my question is, Why segmentation fault after successfully execute print statements?
my code:
#include <stdio.h>
void nomain()
{
printf("Hello World...\n");
printf("Successfully run without main...\n");
}
output:
Hello World...
Successfully run without main...
Segmentation fault (core dumped)
Note:
Here, -nostartfiles
gcc flag prevents the compiler from using standard startup files when linking
Let's have a look at the generated assembly of your program:
.LC0:
.string "Hello World..."
.LC1:
.string "Successfully run without main..."
nomain:
push rbp
mov rbp, rsp
mov edi, OFFSET FLAT:.LC0
call puts
mov edi, OFFSET FLAT:.LC1
call puts
nop
pop rbp
ret
Note the ret
statement. Your program's entry point is determined to be nomain
, all is fine with that. But once the function returns, it attempts to jump into an address on the call stack... that isn't populated. That's an illegal access and a segmentation fault follows.
A quick solution would be to call exit()
at the end of your program (and assuming C11 we might as well mark the function as _Noreturn
):
#include <stdio.h>
#include <stdlib.h>
_Noreturn void nomain(void)
{
printf("Hello World...\n");
printf("Successfully run without main...\n");
exit(0);
}
In fact, now your function behaves pretty much like a regular main
function, since after returning from main
, the exit
function is called with main
's return value.
这篇关于在C中没有main()的情况下编译并运行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!