_start() 在 C 中有什么用? [英] What is the use of _start() in C?

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

问题描述

我从我的同事那里了解到,无需编写 main() 函数即可编写和执行 C 程序.可以这样做:

I learned from my colleague that one can write and execute a C program without writing a main() function. It can be done like this:

my_main.c

/* Compile this with gcc -nostartfiles */

#include <stdlib.h>

void _start() {
  int ret = my_main();
  exit(ret); 
}

int my_main() {
  puts("This is a program without a main() function!");
  return 0; 
}

用这个命令编译它:

gcc -o my_main my_main.c –nostartfiles

使用以下命令运行它:

./my_main

什么时候需要做这种事情?是否有任何真实世界的场景可以使用这种方法?

When would one need to do this kind of thing? Is there any real world scenario where this would be useful?

推荐答案

符号 _start 是程序的入口点.也就是说,那个符号的地址就是程序开始时跳转到的地址.通常,名为 _start 的函数由名为 crt0.o 的文件提供,该文件包含 C 运行时环境的启动代码.它设置一些东西,填充参数数组argv,计算有多少参数,然后调用main.main 返回后,exit 被调用.

The symbol _start is the entry point of your program. That is, the address of that symbol is the address jumped to on program start. Normally, the function with the name _start is supplied by a file called crt0.o which contains the startup code for the C runtime environment. It sets up some stuff, populates the argument array argv, counts how many arguments are there, and then calls main. After main returns, exit is called.

如果一个程序不想使用C运行时环境,它需要为_start提供自己的代码.例如,Go 编程语言的参考实现这样做是因为它们需要一个非标准的线程模型,这需要对堆栈进行一些魔术.当您想编写非常小的程序或执行非常规操作的程序时,提供您自己的 _start 也很有用.

If a program does not want to use the C runtime environment, it needs to supply its own code for _start. For instance, the reference implementation of the Go programming language does so because they need a non-standard threading model which requires some magic with the stack. It's also useful to supply your own _start when you want to write really tiny programs or programs that do unconventional things.

这篇关于_start() 在 C 中有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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