在C ++中main之前会发生什么? [英] What happens before main in C++?

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

问题描述

我知道在C语言中,要在 main()中启动应用程序,某些实体必须:

I know in C, before application can get started in main(), some entity must:


  1. 初始化全局变量

  2. 将堆栈指针设置为最低的堆栈区域地址(假设堆栈向上增长)

问题1-做这个东西的那个实体是什么?谁写的?

Question 1- What's that entity that does this stuff? Who writes it?

问题2-C ++中还有其他东西吗?
我假设在 main()

Question 2- Are there additional things in C++? I assume object constructors and initializations are all done during the course of application, after main()

推荐答案

很大程度上取决于执行环境。在C运行时启动之前,操作系统加载程序可能会做很多工作,这是可执行文件运行的一部分。设置执行环境的这一与操作系统有关的部分对于所有本机(机器语言)可执行文件都是通用的,而与源实现语言无关。

A lot depends on the execution environment. A great deal of work may be done by the operating system loader before the C run-time start up that is specifically part of your executable runs. This operating system dependent part of setting up the execution environment is common to all native (machine language) executables, regardless of source implementation language.

操作系统扮演什么角色,执行什么角色可执行文件中包含的代码的不同,取决于执行环境。 OS加载器(在非独立系统中)负责将代码加载到内存中,并且可能涉及加载和链接动态链接的库(DLL或共享库,具体取决于OS术语)。不管是操作系统还是C运行时责任,通常都会发生以下情况:

What part is played by the OS and what is performed by code that is part of your executable differs depending on the execution environment. The OS loader (in a non-standalone system)is responsible for loading the code into memory, and may involve loading and linking dynamically-linked libraries (DLL or shared-libraries depending on the OS nomenclature). Regardless of whether it is an OS or an C-runtime responsibility, the following normally occur:


  • 建立堆栈

  • 初始化静态数据的零初始化

  • 初始化显式初始化静态数据

  • C库初始化(通常stdio和堆管理需要一些初始化)

  • 对于C ++调用静态构造函数。

  • main()创建堆栈框架( argv argc 参数)

  • Establishment of a stack
  • Zero initialisation of initialised static data
  • Initialisation of explicitly initialised static data
  • C library initialisation (typically stdio and heap-management require some initialisation)
  • For C++ call static constructors.
  • Creation of the stack frame for main() (argv, argc parameters)

例如,在GCC和其他一些编译器中,由程序执行而不是在程序启动之前由操作系统执行的部分由称为 crt0.o

In GCC and some other compilers for example, the part that is performed by your program rather then the OS prior to your program starting, is performed by a separately linked module called crt0.o. This is normally written in assembler and is automatically linked by default.

有关更多示例和讨论,请参见:

For further examples and discussion see:


  • < a href = https://web.archive.org/web/20191210114310/http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html rel = nofollow noreferrer> Linux x86程序启动

  • 典型的独立嵌入式系统启动

  • Linux x86 Program Start Up
  • Typical stand-alone embedded system start-up

这篇关于在C ++中main之前会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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