在 C 中编译和运行没有 main() 的程序 [英] Compile and run program without main() in C

查看:21
本文介绍了在 C 中编译和运行没有 main() 的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 C 中不使用 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

编译器给出警告

/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400340

好的,没问题.然后,我运行了可执行文件(a.out),两个 printf 语句都打印成功,然后得到 segmentation fault.

Ok, No problem. then, I have run executable file(a.out), both printf statements print successfully, and then get segmentation fault.

所以,我的问题是,为什么在成功执行打印语句后出现分段错误?

我的代码:

#include <stdio.h>

void nomain()
{
        printf("Hello World...
");
        printf("Successfully run without main...
");
}

输出:

Hello World...
Successfully run without main...
Segmentation fault (core dumped)

注意:

这里,-nostartfiles gcc 标志防止编译器在链接时使用标准启动文件

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

注意 ret 语句.您的程序的入口点被确定为nomain,一切都很好.但是一旦函数返回,它就会尝试跳转到调用堆栈上的一个地址……没有填充.那是非法访问,然后是分段错误.

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.

一个快速的解决方案是在程序末尾调用 exit()(假设 C11 我们不妨将函数标记为 _Noreturn):

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...
");
    printf("Successfully run without main...
");
    exit(0);
}

事实上,现在你的函数的行为很像一个普通的 main 函数,因为从 main 返回后,exit 函数被调用带有 main 的返回值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆