main() 的返回值会发生什么? [英] What happens with the return value of main()?

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

问题描述

可能重复:
main() 在 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.

根据操作系统加载程序初始化进程的方式,程序参数 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天全站免登陆