main()的返回值会怎样? [英] What happens with the return value of main()?

查看:96
本文介绍了main()的返回值会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在C/C ++中main()应该返回什么?

Possible Duplicate:
What should main() return in C/C++?

#include<stdio.h>
int main()
{
    return 0;
}

在上面给出的代码段中,main返回的return 0在哪里?或者换句话说,哪个函数在一开始就称为主函数.

In the code snippet given above, where does the return 0 returned by main go? Or in other words which function called the main function in the beginning.

推荐答案

main由C运行时库中的某些启动函数调用. C语言标准说,从main返回等同于调用 exit 函数,因此大多数C运行时看起来像这样:

main is called by some startup function in the C runtime library. The C language standard says that returning from main is equivalent to calling the exit function, so most C runtimes look something like this:

void _start(void)  /* Exact function signature may vary */
{
    /* Platform-specifi startup (e.g. fetch argc and argv from the OS) */
    ...
    int status = main(argc, argv);
    exit(status);
    /* Never reached */
}

退出状态被传递回操作系统,然后发生的事情取决于操作系统.

The exit status gets passed back to the operating system, and then what happens from there is OS-dependent.

编译和链接程序时,可执行文件格式(例如PE或ELF)包含一个起始地址,该地址是开始执行的虚拟地址.该函数通常是C运行时库的一部分(例如上面的示例_start).该函数必须通过调用诸如exit之类的系统调用来结束,因为如果它刚刚返回,它将无处可去:它只会从堆栈中弹出一个地址,然后跳转到该位置,这将是垃圾.

When you compile and link your program, the executable file format (e.g. PE or ELF) contains a start address, which is the virtual address at which execution begins. That function is typically part of the C runtime library (like the example _start above). That function has to end by calling a system call such as exit, since if it just returned, it would have nowhere to go to: it would just pop an address off the stack and jump to that location, which would be garbage.

取决于OS加载程序如何初始化进程,程序参数argcargv和其他数据(例如环境)可能作为函数参数(通过寄存器或堆栈)进入,或者它们可能需要系统调用(例如Windows上的GetCommandLine)来检索它们.但是处理所有这些都是C运行时的工作,并且除非您明确地避免使用C运行时,否则您不必担心这些细节.

Depending on how the OS loader initializes processes, the program arguments argc, argv, and other data (such as the environment) might either come in as function parameters (either through registers or the stack), or they might require system calls (e.g. GetCommandLine on Windows) to retrieve them. But dealing with all of that is the job of the C runtime, and unless you're explicitly going out of your way to avoid using the C runtime, you needn't worry about those details.

这篇关于main()的返回值会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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